<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/Frog_16px_1177822_easyicon.net.ico">
  <link rel="mask-icon" href="/images/Frog_32px_1177822_easyicon.net.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"hxy1997.xyz","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"输入关键字","hits_empty":"没有找到与「${query}」相关搜索","hits_stats":"${hits} 条相关记录，共耗时 ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="javascript基本知识，建议有一定基础，再阅读过《JavaScript高级程序设计》（俗称红宝书）的基础上之后进行阅读，开始准备面试吧，初战不利，更应该多刷面经，多背基础，毕竟是实习和校招，基础要夯实，推荐观看  冴羽的博客 ，内容丰富，适合有一定JS基础的人进行阅读">
<meta property="og:type" content="article">
<meta property="og:title" content="javascript面试问题">
<meta property="og:url" content="https://hxy1997.xyz/2021/02/23/javascript%E9%9D%A2%E8%AF%95%E9%97%AE%E9%A2%98/index.html">
<meta property="og:site_name" content="hxy的博客">
<meta property="og:description" content="javascript基本知识，建议有一定基础，再阅读过《JavaScript高级程序设计》（俗称红宝书）的基础上之后进行阅读，开始准备面试吧，初战不利，更应该多刷面经，多背基础，毕竟是实习和校招，基础要夯实，推荐观看  冴羽的博客 ，内容丰富，适合有一定JS基础的人进行阅读">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype1.png">
<meta property="og:image" content="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype2.png">
<meta property="og:image" content="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype3.png">
<meta property="og:image" content="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype4.png">
<meta property="og:image" content="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype5.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419203332.webp">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/7/16edeb6f141feaac?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/7/16edf18bb16af64d?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee12280b78399d?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee172cf1a23c9a?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee17a2fda2c461?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee17decd1d9ed2?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee1819dd9f5999?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee18439a76a3eb?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee1874b4c441d2?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee18969e114bc7?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee18cd2bff353c?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee18f4a21c517e?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee191560b716c7?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee3c5634e61f9e?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee3c90fedad146?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee468e85a1084d?imageslim">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee47d9f933bfc1?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee486ece5fda42?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee48f23fe98d7a?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2019/12/8/16ee490a8b9bf0af?imageView2/0/w/1280/h/960/format/webp/ignore-error/1">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144326.jpeg">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144754.jpeg">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144357.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144900.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144524.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144540.png">
<meta property="article:published_time" content="2021-02-22T16:09:54.000Z">
<meta property="article:modified_time" content="2021-07-22T16:08:39.772Z">
<meta property="article:author" content="hxy">
<meta property="article:tag" content="面试">
<meta property="article:tag" content="javascript">
<meta property="article:tag" content="前端基础">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype1.png">

<link rel="canonical" href="https://hxy1997.xyz/2021/02/23/javascript%E9%9D%A2%E8%AF%95%E9%97%AE%E9%A2%98/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>javascript面试问题 | hxy的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="hxy的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">hxy的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Mia san Mia!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/huxingyi1997" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hxy1997.xyz/2021/02/23/javascript%E9%9D%A2%E8%AF%95%E9%97%AE%E9%A2%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/Robben.gif">
      <meta itemprop="name" content="hxy">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hxy的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          javascript面试问题
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-02-23 00:09:54" itemprop="dateCreated datePublished" datetime="2021-02-23T00:09:54+08:00">2021-02-23</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-07-23 00:08:39" itemprop="dateModified" datetime="2021-07-23T00:08:39+08:00">2021-07-23</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">web前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">热度：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/02/23/javascript%E9%9D%A2%E8%AF%95%E9%97%AE%E9%A2%98/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/02/23/javascript%E9%9D%A2%E8%AF%95%E9%97%AE%E9%A2%98/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>javascript基本知识，建议有一定基础，再阅读过《JavaScript高级程序设计》（俗称红宝书）的基础上之后进行阅读，开始准备面试吧，初战不利，更应该多刷面经，多背基础，毕竟是实习和校招，基础要夯实，推荐观看  <a target="_blank" rel="noopener" href="https://github.com/mqyqingfeng/Blog">冴羽的博客</a> ，内容丰富，适合有一定JS基础的人进行阅读</p>
<span id="more"></span>

<h2 id="1-原型链"><a href="#1-原型链" class="headerlink" title="1.原型链"></a>1.原型链</h2><h3 id="1-1-构造函数创建对象"><a href="#1-1-构造函数创建对象" class="headerlink" title="1.1 构造函数创建对象"></a>1.1 构造函数创建对象</h3><p>我们先使用构造函数创建一个对象：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	...</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> person = <span class="keyword">new</span> Person();</span><br><span class="line">person.name = <span class="string">&#x27;Kevin&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(person.name) <span class="comment">// Kevin</span></span><br></pre></td></tr></table></figure>

<p>在这个例子中，Person 就是一个构造函数，我们使用 new 创建了一个实例对象 person。</p>
<h3 id="1-2-prototype"><a href="#1-2-prototype" class="headerlink" title="1.2 prototype"></a>1.2 prototype</h3><p>每个构造函数都有一个 prototype 属性 ，比如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 虽然写在注释里，但是你要注意：</span></span><br><span class="line"><span class="comment">// prototype是对象的属性</span></span><br><span class="line">Person.prototype.name = <span class="string">&#x27;Kevin&#x27;</span>;</span><br><span class="line"><span class="keyword">var</span> person1 = <span class="keyword">new</span> Person();</span><br><span class="line"><span class="keyword">var</span> person2 = <span class="keyword">new</span> Person();</span><br><span class="line"><span class="built_in">console</span>.log(person1.name) <span class="comment">// Kevin</span></span><br><span class="line"><span class="built_in">console</span>.log(person2.name) <span class="comment">// Kevin</span></span><br></pre></td></tr></table></figure>

<p>那这个函数的 prototype 属性到底指向的是什么呢？是这个函数的原型吗？</p>
<p>其实，函数的 prototype 属性指向了一个对象，这个对象正是调用该构造函数而创建的<strong>实例</strong>的原型，也就是这个例子中的 person1 和 person2 的原型。</p>
<p>那什么是原型呢？你可以这样理解：每一个JavaScript对象(null除外)在创建的时候就会与之关联另一个对象，这个对象就是我们所说的原型，每一个对象都会从原型”继承”属性。</p>
<p>让我们用一张图表示构造函数和实例原型之间的关系：</p>
<p><img data-src="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype1.png" alt="构造函数和实例原型的关系图"></p>
<p>在这张图中我们用 Object.prototype 表示实例原型。</p>
<p>那么我们该怎么表示实例与实例原型，也就是 person 和 Person.prototype 之间的关系呢，这时候我们就要讲到第二个属性：</p>
<h3 id="1-3-proto"><a href="#1-3-proto" class="headerlink" title="1.3 __proto__"></a>1.3 __proto__</h3><p>这是每一个JavaScript对象(除了 null )都具有的一个属性，叫__proto__，这个属性会指向该对象的原型。</p>
<p>为了证明这一点,我们可以在Firefox或者Chrome中控制台输入：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> person = <span class="keyword">new</span> Person();</span><br><span class="line"><span class="built_in">console</span>.log(person.__proto__ === Person.prototype); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>于是我们更新下关系图：</p>
<p><img data-src="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype2.png" alt="实例与实例原型的关系图"></p>
<p>既然实例对象和构造函数都可以指向原型，那么原型是否有属性指向构造函数或者实例呢？</p>
<h3 id="1-4-constructor"><a href="#1-4-constructor" class="headerlink" title="1.4 constructor"></a>1.4 constructor</h3><p>指向实例倒是没有，因为同一个构造函数可以生成多个实例，但是原型指向构造函数倒是有的，这就要讲到第三个属性：constructor，每个原型都有一个 constructor 属性指向关联的构造函数。</p>
<p>为了验证这一点，我们可以尝试：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(Person === Person.prototype.constructor); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>所以再更新下关系图：</p>
<p><img data-src="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype3.png" alt="实例原型与构造函数的关系图"></p>
<p>综上我们已经得出：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> person = <span class="keyword">new</span> Person();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(person.__proto__ === Person.prototype) <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(Person.prototype.constructor === Person) <span class="comment">// true</span></span><br><span class="line"><span class="comment">// 顺便学习一个ES5的方法,可以获得对象的原型</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Object</span>.getPrototypeOf(person) === Person.prototype) <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>了解了构造函数、实例原型、和实例之间的关系，接下来我们讲讲实例和原型的关系：</p>
<h3 id="1-5-实例与原型"><a href="#1-5-实例与原型" class="headerlink" title="1.5 实例与原型"></a>1.5 实例与原型</h3><p>当读取实例的属性时，如果找不到，就会查找与对象关联的原型中的属性，如果还查不到，就去找原型的原型，一直找到最顶层为止。</p>
<p>举个例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Person.prototype.name = <span class="string">&#x27;Kevin&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> person = <span class="keyword">new</span> Person();</span><br><span class="line"></span><br><span class="line">person.name = <span class="string">&#x27;Daisy&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(person.name) <span class="comment">// Daisy</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">delete</span> person.name;</span><br><span class="line"><span class="built_in">console</span>.log(person.name) <span class="comment">// Kevin</span></span><br></pre></td></tr></table></figure>

<p>在这个例子中，我们给实例对象 person 添加了 name 属性，当我们打印 person.name 的时候，结果自然为 Daisy。</p>
<p>但是当我们删除了 person 的 name 属性时，读取 person.name，从 person 对象中找不到 name 属性就会从 person 的原型也就是 person.__proto__ ，也就是 Person.prototype中查找，幸运的是我们找到了 name 属性，结果为 Kevin。</p>
<p>但是万一还没有找到呢？原型的原型又是什么呢？</p>
<h3 id="1-6-原型的原型"><a href="#1-6-原型的原型" class="headerlink" title="1.6 原型的原型"></a>1.6 原型的原型</h3><p>在前面，我们已经讲了原型也是一个对象，既然是对象，我们就可以用最原始的方式创建它，那就是：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">obj.name = <span class="string">&#x27;Kevin&#x27;</span></span><br><span class="line"><span class="built_in">console</span>.log(obj.name) <span class="comment">// Kevin</span></span><br></pre></td></tr></table></figure>

<p>其实原型对象就是通过 Object 构造函数生成的，结合之前所讲，实例的 <strong>proto</strong> 指向构造函数的 prototype ，所以我们再更新下关系图：</p>
<p><img data-src="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype4.png" alt="原型的原型关系图"></p>
<h3 id="1-7-原型链"><a href="#1-7-原型链" class="headerlink" title="1.7 原型链"></a>1.7 原型链</h3><p>那 Object.prototype 的原型呢？</p>
<p>null，我们可以打印：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Object</span>.prototype.__proto__ === <span class="literal">null</span>) <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>然而 null 究竟代表了什么呢？</p>
<p>引用阮一峰老师的 <a target="_blank" rel="noopener" href="http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html">《undefined与null的区别》</a> 就是：</p>
<blockquote>
<p>null 表示“没有对象”，即该处不应该有值。</p>
</blockquote>
<p>所以 Object.prototype.__proto__ 的值为 null 就是 Object.prototype 没有原型，表达了同一个意思。</p>
<p>所以查找属性的时候查到 Object.prototype 就可以停止查找了。</p>
<p>最后一张关系图也可以更新为：</p>
<p><img data-src="https://github.com/mqyqingfeng/Blog/raw/master/Images/prototype5.png" alt="原型链示意图"></p>
<p>顺便还要说一下，图中由相互关联的原型组成的链状结构就是原型链，也就是蓝色的这条线。</p>
<h3 id="补充"><a href="#补充" class="headerlink" title="补充"></a>补充</h3><p>最后，补充三点大家可能不会注意的地方：</p>
<h4 id="constructor-NaN"><a href="#constructor-NaN" class="headerlink" title="constructor"></a>constructor</h4><p>首先是 constructor 属性，我们看个例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 实例</span></span><br><span class="line"><span class="keyword">var</span> person = <span class="keyword">new</span> Person();</span><br><span class="line"><span class="built_in">console</span>.log(person.constructor === Person); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>当获取 person.constructor 时，其实 person 中并没有 constructor 属性,当不能读取到constructor 属性时，会从 person 的原型也就是 Person.prototype 中读取，正好原型中有该属性，所以：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">person.constructor === Person.prototype.constructor</span><br></pre></td></tr></table></figure>

<h4 id="proto"><a href="#proto" class="headerlink" title="__proto__"></a>__proto__</h4><p>其次是 __proto__ ，绝大部分浏览器都支持这个非标准的方法访问原型，然而它并不存在于 Person.prototype 中，实际上，它是来自于 Object.prototype ，与其说是一个属性，不如说是一个 getter/setter，当使用 obj.<strong>proto</strong> 时，可以理解成返回了 Object.getPrototypeOf(obj)。</p>
<h3 id="真的是继承吗？"><a href="#真的是继承吗？" class="headerlink" title="真的是继承吗？"></a>真的是继承吗？</h3><p>最后是关于继承，前面我们讲到“每一个对象都会从原型‘继承’属性”，实际上，继承是一个十分具有迷惑性的说法，引用《你不知道的JavaScript》中的话，就是：</p>
<p>继承意味着复制操作，然而 JavaScript 默认并不会复制对象的属性，相反，JavaScript 只是在两个对象之间创建一个关联，这样，一个对象就可以通过委托访问另一个对象的属性和函数，所以与其叫继承，委托的说法反而更准确些。</p>
<h2 id="2-继承"><a href="#2-继承" class="headerlink" title="2.继承"></a>2.继承</h2><h3 id="2-1-原型链继承"><a href="#2-1-原型链继承" class="headerlink" title="2.1 原型链继承"></a>2.1 原型链继承</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Parent</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.name = <span class="string">&#x27;kevin&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Parent.prototype.getName = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.name);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Child</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 关键 子类的原型指向父类</span></span><br><span class="line">Child.prototype = <span class="keyword">new</span> Parent();</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> child1 = <span class="keyword">new</span> Child();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(child1.getName()) <span class="comment">// kevin</span></span><br></pre></td></tr></table></figure>

<p>缺点：</p>
<p>1.引用类型的属性被所有实例共享，举个例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Parent</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.names = [<span class="string">&#x27;kevin&#x27;</span>, <span class="string">&#x27;daisy&#x27;</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Child</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line">Child.prototype = <span class="keyword">new</span> Parent();</span><br><span class="line"><span class="keyword">var</span> child1 = <span class="keyword">new</span> Child();</span><br><span class="line">child1.names.push(<span class="string">&#x27;yayu&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(child1.names); <span class="comment">// [&quot;kevin&quot;, &quot;daisy&quot;, &quot;yayu&quot;]</span></span><br><span class="line"><span class="keyword">var</span> child2 = <span class="keyword">new</span> Child();</span><br><span class="line"><span class="built_in">console</span>.log(child2.names); <span class="comment">// [&quot;kevin&quot;, &quot;daisy&quot;, &quot;yayu&quot;]</span></span><br></pre></td></tr></table></figure>

<p>2.在创建 Child 的实例时，不能向Parent传参</p>
<h3 id="2-2-借用构造函数-经典继承"><a href="#2-2-借用构造函数-经典继承" class="headerlink" title="2.2 借用构造函数(经典继承)"></a>2.2 借用构造函数(经典继承)</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Parent</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.names = [<span class="string">&#x27;kevin&#x27;</span>, <span class="string">&#x27;daisy&#x27;</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Child</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="comment">// 关键 在子类构造函数中调用父类构造函数</span></span><br><span class="line">    Parent.call(<span class="built_in">this</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> child1 = <span class="keyword">new</span> Child();</span><br><span class="line">child1.names.push(<span class="string">&#x27;yayu&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(child1.names); <span class="comment">// [&quot;kevin&quot;, &quot;daisy&quot;, &quot;yayu&quot;]</span></span><br><span class="line"><span class="keyword">var</span> child2 = <span class="keyword">new</span> Child();</span><br><span class="line"><span class="built_in">console</span>.log(child2.names); <span class="comment">// [&quot;kevin&quot;, &quot;daisy&quot;]</span></span><br></pre></td></tr></table></figure>

<p>优点：</p>
<p>1.避免了引用类型的属性被所有实例共享</p>
<p>2.可以在 Child 中向 Parent 传参</p>
<p>举个例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Parent</span> (<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Child</span> (<span class="params">name</span>) </span>&#123;</span><br><span class="line">    Parent.call(<span class="built_in">this</span>, name);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> child1 = <span class="keyword">new</span> Child(<span class="string">&#x27;kevin&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(child1.name); <span class="comment">// kevin</span></span><br><span class="line"><span class="keyword">var</span> child2 = <span class="keyword">new</span> Child(<span class="string">&#x27;daisy&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(child2.name); <span class="comment">// daisy</span></span><br></pre></td></tr></table></figure>

<p>缺点：</p>
<p>方法都在构造函数中定义每个子类实例不能共享父函数，浪费内存，开销较大。不能继承父类原型。</p>
<h3 id="2-3-组合继承"><a href="#2-3-组合继承" class="headerlink" title="2.3 组合继承"></a>2.3 组合继承</h3><p>原型链继承和经典继承双剑合璧。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Parent</span> (<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">    <span class="built_in">this</span>.colors = [<span class="string">&#x27;red&#x27;</span>, <span class="string">&#x27;blue&#x27;</span>, <span class="string">&#x27;green&#x27;</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Parent.prototype.getName = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.name)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Child</span> (<span class="params">name, age</span>) </span>&#123;</span><br><span class="line">	<span class="comment">// 关键 在子类构造函数中调用父类构造函数</span></span><br><span class="line">    Parent.call(<span class="built_in">this</span>, name);</span><br><span class="line">    <span class="built_in">this</span>.age = age;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 子类的原型指向父类</span></span><br><span class="line">Child.prototype = <span class="keyword">new</span> Parent();</span><br><span class="line">Child.prototype.constructor = Child;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> child1 = <span class="keyword">new</span> Child(<span class="string">&#x27;kevin&#x27;</span>, <span class="string">&#x27;18&#x27;</span>);</span><br><span class="line"></span><br><span class="line">child1.colors.push(<span class="string">&#x27;black&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(child1.name); <span class="comment">// kevin</span></span><br><span class="line"><span class="built_in">console</span>.log(child1.age); <span class="comment">// 18</span></span><br><span class="line"><span class="built_in">console</span>.log(child1.colors); <span class="comment">// [&quot;red&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;black&quot;]</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> child2 = <span class="keyword">new</span> Child(<span class="string">&#x27;daisy&#x27;</span>, <span class="string">&#x27;20&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(child2.name); <span class="comment">// daisy</span></span><br><span class="line"><span class="built_in">console</span>.log(child2.age); <span class="comment">// 20</span></span><br><span class="line"><span class="built_in">console</span>.log(child2.colors); <span class="comment">// [&quot;red&quot;, &quot;blue&quot;, &quot;green&quot;]</span></span><br></pre></td></tr></table></figure>

<p>优点：融合原型链继承和构造函数的优点，是 JavaScript 中最常用的继承模式。</p>
<p>缺点：Parent的构造函数会多执行了一次</p>
<h3 id="2-4-原型式继承"><a href="#2-4-原型式继承" class="headerlink" title="2.4 原型式继承"></a>2.4 原型式继承</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createObj</span>(<span class="params">o</span>) </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">F</span>(<span class="params"></span>)</span>&#123;&#125;</span><br><span class="line">    F.prototype = o;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> F();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>就是 ES5 Object.create 的模拟实现，将传入的对象作为创建的对象的原型。</p>
<p>缺点：包含引用类型的属性值始终都会共享相应的值，这点跟原型链继承一样。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> person = &#123;</span><br><span class="line">    name: <span class="string">&#x27;kevin&#x27;</span>,</span><br><span class="line">    friends: [<span class="string">&#x27;daisy&#x27;</span>, <span class="string">&#x27;kelly&#x27;</span>]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> person1 = createObj(person);</span><br><span class="line"><span class="keyword">var</span> person2 = createObj(person);</span><br><span class="line"></span><br><span class="line">person1.name = <span class="string">&#x27;person1&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(person2.name); <span class="comment">// kevin</span></span><br><span class="line"></span><br><span class="line">person1.firends.push(<span class="string">&#x27;taylor&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(person2.friends); <span class="comment">// [&quot;daisy&quot;, &quot;kelly&quot;, &quot;taylor&quot;]</span></span><br></pre></td></tr></table></figure>

<p>注意：修改<code>person1.name</code>的值，<code>person2.name</code>的值并未发生改变，并不是因为<code>person1</code>和<code>person2</code>有独立的 name 值，而是因为<code>person1.name = &#39;person1&#39;</code>，给<code>person1</code>添加了 name 值，并非修改了原型上的 name 值。</p>
<h3 id="2-5-寄生式继承"><a href="#2-5-寄生式继承" class="headerlink" title="2.5 寄生式继承"></a>2.5 寄生式继承</h3><p>创建一个仅用于封装继承过程的函数，该函数在内部以某种形式来做增强对象，最后返回对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createObj</span> (<span class="params">o</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> clone = <span class="built_in">Object</span>.create(o);</span><br><span class="line">    clone.sayName = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;hi&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> clone;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>缺点：跟借用构造函数模式一样，每次创建对象都会创建一遍方法。</p>
<h3 id="2-6-寄生组合式继承"><a href="#2-6-寄生组合式继承" class="headerlink" title="2.6 寄生组合式继承"></a>2.6 寄生组合式继承</h3><p>为了方便大家阅读，在这里重复一下组合继承的代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Parent</span> (<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">    <span class="built_in">this</span>.colors = [<span class="string">&#x27;red&#x27;</span>, <span class="string">&#x27;blue&#x27;</span>, <span class="string">&#x27;green&#x27;</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Parent.prototype.getName = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.name);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Child</span> (<span class="params">name, age</span>) </span>&#123;</span><br><span class="line">    Parent.call(<span class="built_in">this</span>, name);</span><br><span class="line">    <span class="built_in">this</span>.age = age;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Child.prototype = <span class="keyword">new</span> Parent();</span><br><span class="line"><span class="keyword">var</span> child1 = <span class="keyword">new</span> Child(<span class="string">&#x27;kevin&#x27;</span>, <span class="string">&#x27;18&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(child1);</span><br></pre></td></tr></table></figure>

<p>组合继承最大的缺点是会调用两次父构造函数。</p>
<p>一次是设置子类型实例的原型的时候：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Child.prototype = <span class="keyword">new</span> Parent();</span><br></pre></td></tr></table></figure>

<p>一次在创建子类型实例的时候：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> child1 = <span class="keyword">new</span> Child(<span class="string">&#x27;kevin&#x27;</span>, <span class="string">&#x27;18&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>回想下 new 的模拟实现，其实在这句中，我们会执行：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Parent.call(<span class="built_in">this</span>, name);</span><br></pre></td></tr></table></figure>

<p>在这里，我们又会调用了一次 Parent 构造函数。</p>
<p>所以，在这个例子中，如果我们打印 child1 对象，我们会发现 Child.prototype 和 child1 都有一个属性为<code>colors</code>，属性值为<code>[&#39;red&#39;, &#39;blue&#39;, &#39;green&#39;]</code>。</p>
<p>那么我们该如何精益求精，避免这一次重复调用呢？</p>
<p>如果我们不使用 Child.prototype = new Parent() ，而是间接的让 Child.prototype 访问到 Parent.prototype 呢？</p>
<p>看看如何实现：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Parent</span> (<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">    <span class="built_in">this</span>.colors = [<span class="string">&#x27;red&#x27;</span>, <span class="string">&#x27;blue&#x27;</span>, <span class="string">&#x27;green&#x27;</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Parent.prototype.getName = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.name)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Child</span> (<span class="params">name, age</span>) </span>&#123;</span><br><span class="line">    Parent.call(<span class="built_in">this</span>, name);</span><br><span class="line">    <span class="built_in">this</span>.age = age;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 关键的三步</span></span><br><span class="line"><span class="keyword">var</span> F = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;;</span><br><span class="line">F.prototype = Parent.prototype;</span><br><span class="line">Child.prototype = <span class="keyword">new</span> F();</span><br><span class="line"><span class="keyword">var</span> child1 = <span class="keyword">new</span> Child(<span class="string">&#x27;kevin&#x27;</span>, <span class="string">&#x27;18&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(child1);</span><br></pre></td></tr></table></figure>

<p>最后我们封装一下这个继承方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">object</span>(<span class="params">o</span>) </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">F</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">    F.prototype = o;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> F();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">prototype</span>(<span class="params">child, parent</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> prototype = object(parent.prototype);</span><br><span class="line">    prototype.constructor = child;</span><br><span class="line">    child.prototype = prototype;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 当我们使用的时候：</span></span><br><span class="line">prototype(Child, Parent);</span><br></pre></td></tr></table></figure>

<p>引用《JavaScript高级程序设计》中对寄生组合式继承的夸赞就是：</p>
<p>这种方式的高效率体现它只调用了一次 Parent 构造函数，并且因此避免了在 Parent.prototype 上面创建不必要的、多余的属性。与此同时，原型链还能保持不变；因此，还能够正常使用 instanceof 和 isPrototypeOf。开发人员普遍认为寄生组合式继承是引用类型最理想的继承范式。</p>
<h1 id="3-作用域链"><a href="#3-作用域链" class="headerlink" title="3.作用域链"></a>3.作用域链</h1><h2 id="3-1-定义"><a href="#3-1-定义" class="headerlink" title="3.1 定义"></a>3.1 定义</h2><p>当查找变量的时候，会先从当前上下文的变量对象中查找，如果没有找到，就会从父级(词法层面上的父级)执行上下文的变量对象中查找，一直找到全局上下文的变量对象，也就是全局对象。这样由多个执行上下文的变量对象构成的链表就叫做作用域链。</p>
<p>下面，让我们以一个函数的创建和激活两个时期来讲解作用域链是如何创建和变化的。</p>
<h2 id="3-2-函数创建"><a href="#3-2-函数创建" class="headerlink" title="3.2 函数创建"></a>3.2 函数创建</h2><p>函数的作用域在函数定义的时候就决定了,这是因为函数有一个内部属性 [[scope]]，当函数创建的时候，就会保存所有父变量对象到其中，你可以理解 [[scope]] 就是所有父变量对象的层级链，但是注意：[[scope]] 并不代表完整的作用域链！</p>
<p>举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    function bar() &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>函数创建时，各自的[[scope]]为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">foo.[[scope]] &#x3D; [</span><br><span class="line">	globalContext.VO</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line">bar.[[scope]] &#x3D; [</span><br><span class="line">    fooContext.AO,</span><br><span class="line">    globalContext.VO</span><br><span class="line">];</span><br></pre></td></tr></table></figure>

<h2 id="3-3-函数激活"><a href="#3-3-函数激活" class="headerlink" title="3.3 函数激活"></a>3.3 函数激活</h2><p>当函数激活时，进入函数上下文，创建 VO/AO 后，就会将活动对象添加到作用链的前端。</p>
<p>这时候执行上下文的作用域链，我们命名为 Scope：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Scope &#x3D; [AO].concat([[Scope]]);</span><br></pre></td></tr></table></figure>

<p>至此，作用域链创建完毕。</p>
<h2 id="3-4-按照步骤分析"><a href="#3-4-按照步骤分析" class="headerlink" title="3.4 按照步骤分析"></a>3.4 按照步骤分析</h2><p>以下面的例子为例，结合着之前讲的变量对象和执行上下文栈，我们来总结一下函数执行上下文中作用域链和变量对象的创建过程：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var scope &#x3D; &quot;global scope&quot;;</span><br><span class="line">function checkscope()&#123;</span><br><span class="line">    var scope2 &#x3D; &#39;local scope&#39;;</span><br><span class="line">    return scope2;</span><br><span class="line">&#125;</span><br><span class="line">checkscope();</span><br></pre></td></tr></table></figure>

<p>执行过程如下：</p>
<p>1.checkscope 函数被创建，保存作用域链到 内部属性[[scope]]</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">checkscope.[[scope]] &#x3D; [</span><br><span class="line">    globalContext.VO</span><br><span class="line">];</span><br></pre></td></tr></table></figure>

<p>2.执行 checkscope 函数，创建 checkscope 函数执行上下文，checkscope 函数执行上下文被压入执行上下文栈</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ECStack &#x3D; [</span><br><span class="line">    checkscopeContext,</span><br><span class="line">    globalContext</span><br><span class="line">];</span><br></pre></td></tr></table></figure>

<p>3.checkscope 函数并不立刻执行，开始做准备工作，第一步：复制函数[[scope]]属性创建作用域链</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">checkscopeContext &#x3D; &#123;</span><br><span class="line">    Scope: checkscope.[[scope]],</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4.第二步：用 arguments 创建活动对象，随后初始化活动对象，加入形参、函数声明、变量声明</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">checkscopeContext &#x3D; &#123;</span><br><span class="line">    AO: &#123;</span><br><span class="line">        arguments: &#123;</span><br><span class="line">            length: 0</span><br><span class="line">        &#125;,</span><br><span class="line">        scope2: undefined</span><br><span class="line">    &#125;，</span><br><span class="line">    Scope: checkscope.[[scope]],</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>5.第三步：将活动对象压入 checkscope 作用域链顶端</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">checkscopeContext &#x3D; &#123;</span><br><span class="line">    AO: &#123;</span><br><span class="line">        arguments: &#123;</span><br><span class="line">            length: 0</span><br><span class="line">        &#125;,</span><br><span class="line">        scope2: undefined</span><br><span class="line">    &#125;,</span><br><span class="line">    Scope: [AO, [[Scope]]]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>6.准备工作做完，开始执行函数，随着函数的执行，修改 AO 的属性值</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">checkscopeContext &#x3D; &#123;</span><br><span class="line">    AO: &#123;</span><br><span class="line">        arguments: &#123;</span><br><span class="line">            length: 0</span><br><span class="line">        &#125;,</span><br><span class="line">        scope2: &#39;local scope&#39;</span><br><span class="line">    &#125;,</span><br><span class="line">    Scope: [AO, [[Scope]]]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>7.查找到 scope2 的值，返回后函数执行完毕，函数上下文从执行上下文栈中弹出</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ECStack &#x3D; [</span><br><span class="line">    globalContext</span><br><span class="line">];</span><br></pre></td></tr></table></figure>



<h1 id="4-闭包"><a href="#4-闭包" class="headerlink" title="4.闭包"></a>4.闭包</h1><h2 id="4-1-定义"><a href="#4-1-定义" class="headerlink" title="4.1 定义"></a>4.1 定义</h2><p>MDN 对闭包的定义为：</p>
<blockquote>
<p>闭包是指那些能够访问自由变量的函数。</p>
</blockquote>
<p>那什么是自由变量呢？</p>
<blockquote>
<p>自由变量是指在函数中使用的，但既不是函数参数也不是函数的局部变量的变量。</p>
</blockquote>
<p>由此，我们可以看出闭包共有两部分组成：</p>
<blockquote>
<p>闭包 = 函数 + 函数能够访问的自由变量</p>
</blockquote>
<p>举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var a &#x3D; 1;</span><br><span class="line"></span><br><span class="line">function foo() &#123;</span><br><span class="line">    console.log(a);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo();</span><br></pre></td></tr></table></figure>

<p>foo 函数可以访问变量 a，但是 a 既不是 foo 函数的局部变量，也不是 foo 函数的参数，所以 a 就是自由变量。</p>
<p>那么，函数 foo + foo 函数访问的自由变量 a 不就是构成了一个闭包嘛……</p>
<p>还真是这样的！</p>
<p>所以在《JavaScript权威指南》中就讲到：从技术的角度讲，所有的JavaScript函数都是闭包。因为它们都在创建的时候就将上层上下文的数据保存起来了。哪怕是简单的全局变量也是如此，因为函数中访问全局变量就相当于是在访问自由变量，这个时候使用最外层的作用域。</p>
<p>这只是理论上的闭包，其实还有一个实践角度上的闭包，让我们看看汤姆大叔翻译的关于闭包的文章中的定义：</p>
<p>ECMAScript中，从实践角度，以下函数才算是闭包：</p>
<p>1.即使创建它的上下文已经销毁，它仍然存在（比如，内部函数从父函数中返回）</p>
<p>2.在代码中引用了自由变量</p>
<p>接下来就来讲讲实践上的闭包。</p>
<h2 id="4-2-分析"><a href="#4-2-分析" class="headerlink" title="4.2 分析"></a>4.2 分析</h2><p>让我们先写个例子，例子依然是来自《JavaScript权威指南》，稍微做点改动：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var scope &#x3D; &quot;global scope&quot;;</span><br><span class="line">function checkscope()&#123;</span><br><span class="line">    var scope &#x3D; &quot;local scope&quot;;</span><br><span class="line">    function f()&#123;</span><br><span class="line">        return scope;</span><br><span class="line">    &#125;</span><br><span class="line">    return f;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var foo &#x3D; checkscope();</span><br><span class="line">foo();</span><br></pre></td></tr></table></figure>

<p>首先我们要分析一下这段代码中执行上下文栈和执行上下文的变化情况。</p>
<p>这里直接给出简要的执行过程：</p>
<ol>
<li>进入全局代码，创建全局执行上下文，全局执行上下文压入执行上下文栈</li>
<li>全局执行上下文初始化</li>
<li>执行 checkscope 函数，创建 checkscope 函数执行上下文，checkscope 执行上下文被压入执行上下文栈</li>
<li>checkscope 执行上下文初始化，创建变量对象、作用域链、this等</li>
<li>checkscope 函数执行完毕，checkscope 执行上下文从执行上下文栈中弹出</li>
<li>执行 f 函数，创建 f 函数执行上下文，f 执行上下文被压入执行上下文栈</li>
<li>f 执行上下文初始化，创建变量对象、作用域链、this等</li>
<li>f 函数执行完毕，f 函数上下文从执行上下文栈中弹出</li>
</ol>
<p>了解到这个过程，我们应该思考一个问题，那就是：</p>
<p>当 f 函数执行的时候，checkscope 函数上下文已经被销毁了啊(即从执行上下文栈中被弹出)，怎么还会读取到 checkscope 作用域下的 scope 值呢？</p>
<p>以上的代码，要是转换成 PHP，就会报错，因为在 PHP 中，f 函数只能读取到自己作用域和全局作用域里的值，所以读不到 checkscope 下的 scope 值。(这段我问的PHP同事……)</p>
<p>然而 JavaScript 却是可以的！</p>
<p>当我们了解了具体的执行过程后，我们知道 f 执行上下文维护了一个作用域链：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fContext &#x3D; &#123;</span><br><span class="line">    Scope: [AO, checkscopeContext.AO, globalContext.VO],</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对的，就是因为这个作用域链，f 函数依然可以读取到 checkscopeContext.AO 的值，说明当 f 函数引用了 checkscopeContext.AO 中的值的时候，即使 checkscopeContext 被销毁了，但是 JavaScript 依然会让 checkscopeContext.AO 活在内存中，f 函数依然可以通过 f 函数的作用域链找到它，正是因为 JavaScript 做到了这一点，从而实现了闭包这个概念。</p>
<p>所以，让我们再看一遍实践角度上闭包的定义：</p>
<ol>
<li>即使创建它的上下文已经销毁，它仍然存在（比如，内部函数从父函数中返回）</li>
<li>在代码中引用了自由变量</li>
</ol>
<p>在这里再补充一个《JavaScript权威指南》英文原版对闭包的定义:</p>
<blockquote>
<p>This combination of a function object and a scope (a set of variable bindings) in which the function’s variables are resolved is called a closure in the computer science literature.</p>
</blockquote>
<p>闭包在计算机科学中也只是一个普通的概念，大家不要去想得太复杂。</p>
<h2 id="4-3-必刷题"><a href="#4-3-必刷题" class="headerlink" title="4.3 必刷题"></a>4.3 必刷题</h2><p>接下来，看这道刷题必刷，面试必考的闭包题：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var data &#x3D; [];</span><br><span class="line"></span><br><span class="line">for (var i &#x3D; 0; i &lt; 3; i++) &#123;</span><br><span class="line">  data[i] &#x3D; function () &#123;</span><br><span class="line">    console.log(i);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">data[0]();</span><br><span class="line">data[1]();</span><br><span class="line">data[2]();</span><br></pre></td></tr></table></figure>

<p>答案是都是 3，让我们分析一下原因：</p>
<p>当执行到 data[0] 函数之前，此时全局上下文的 VO 为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">globalContext &#x3D; &#123;</span><br><span class="line">    VO: &#123;</span><br><span class="line">        data: [...],</span><br><span class="line">        i: 3</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当执行 data[0] 函数的时候，data[0] 函数的作用域链为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">data[0]Context &#x3D; &#123;</span><br><span class="line">    Scope: [AO, globalContext.VO]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>data[0]Context 的 AO 并没有 i 值，所以会从 globalContext.VO 中查找，i 为 3，所以打印的结果就是 3。</p>
<p>data[1] 和 data[2] 是一样的道理。</p>
<p>所以让我们改成闭包看看：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">var data &#x3D; [];</span><br><span class="line"></span><br><span class="line">for (var i &#x3D; 0; i &lt; 3; i++) &#123;</span><br><span class="line">  data[i] &#x3D; (function (i) &#123;</span><br><span class="line">        return function()&#123;</span><br><span class="line">            console.log(i);</span><br><span class="line">        &#125;</span><br><span class="line">  &#125;)(i);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">data[0]();</span><br><span class="line">data[1]();</span><br><span class="line">data[2]();</span><br></pre></td></tr></table></figure>

<p>当执行到 data[0] 函数之前，此时全局上下文的 VO 为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">globalContext &#x3D; &#123;</span><br><span class="line">    VO: &#123;</span><br><span class="line">        data: [...],</span><br><span class="line">        i: 3</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>跟没改之前一模一样。</p>
<p>当执行 data[0] 函数的时候，data[0] 函数的作用域链发生了改变：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">data[0]Context &#x3D; &#123;</span><br><span class="line">    Scope: [AO, 匿名函数Context.AO globalContext.VO]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>匿名函数执行上下文的AO为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">匿名函数Context &#x3D; &#123;</span><br><span class="line">    AO: &#123;</span><br><span class="line">        arguments: &#123;</span><br><span class="line">            0: 0,</span><br><span class="line">            length: 1</span><br><span class="line">        &#125;,</span><br><span class="line">        i: 0</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>data[0]Context 的 AO 并没有 i 值，所以会沿着作用域链从匿名函数 Context.AO 中查找，这时候就会找 i 为 0，找到了就不会往 globalContext.VO 中查找了，即使 globalContext.VO 也有 i 的值(值为3)，所以打印的结果就是0。</p>
<p>data[1] 和 data[2] 是一样的道理。</p>
<h1 id="5-变量对象"><a href="#5-变量对象" class="headerlink" title="5.变量对象"></a>5.变量对象</h1><h2 id="5-1-变量对象"><a href="#5-1-变量对象" class="headerlink" title="5.1 变量对象"></a>5.1 变量对象</h2><p>变量对象是与执行上下文相关的数据作用域，存储了在上下文中定义的变量和函数声明。</p>
<p>因为不同执行上下文下的变量对象稍有不同，所以我们来聊聊全局上下文下的变量对象和函数上下文下的变量对象。</p>
<h2 id="5-2-全局上下文"><a href="#5-2-全局上下文" class="headerlink" title="5.2 全局上下文"></a>5.2 全局上下文</h2><p>我们先了解一个概念，叫全局对象。在 <a target="_blank" rel="noopener" href="http://www.w3school.com.cn/jsref/jsref_obj_global.asp">W3School</a> 中也有介绍：</p>
<blockquote>
<p>全局对象是预定义的对象，作为 JavaScript 的全局函数和全局属性的占位符。通过使用全局对象，可以访问所有其他所有预定义的对象、函数和属性。</p>
</blockquote>
<blockquote>
<p>在顶层 JavaScript 代码中，可以用关键字 this 引用全局对象。因为全局对象是作用域链的头，这意味着所有非限定性的变量和函数名都会作为该对象的属性来查询。</p>
</blockquote>
<blockquote>
<p>例如，当JavaScript 代码引用 parseInt() 函数时，它引用的是全局对象的 parseInt 属性。全局对象是作用域链的头，还意味着在顶层 JavaScript 代码中声明的所有变量都将成为全局对象的属性。</p>
</blockquote>
<p>如果看的不是很懂的话，容我再来介绍下全局对象:</p>
<p>1.可以通过 this 引用，在客户端 JavaScript 中，全局对象就是 Window 对象。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">console.log(this);</span><br></pre></td></tr></table></figure>

<p>2.全局对象是由 Object 构造函数实例化的一个对象。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">console.log(this instanceof Object);</span><br></pre></td></tr></table></figure>

<p>3.预定义了一堆，嗯，一大堆函数和属性。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 都能生效</span><br><span class="line">console.log(Math.random());</span><br><span class="line">console.log(this.Math.random());</span><br></pre></td></tr></table></figure>

<p>4.作为全局变量的宿主。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var a &#x3D; 1;</span><br><span class="line">console.log(this.a);</span><br></pre></td></tr></table></figure>

<p>5.客户端 JavaScript 中，全局对象有 window 属性指向自身。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var a &#x3D; 1;</span><br><span class="line">console.log(window.a);</span><br><span class="line"></span><br><span class="line">this.window.b &#x3D; 2;</span><br><span class="line">console.log(this.b);</span><br></pre></td></tr></table></figure>

<p>花了一个大篇幅介绍全局对象，其实就想说：</p>
<p>全局上下文中的变量对象就是全局对象呐！</p>
<h2 id="5-3-函数上下文"><a href="#5-3-函数上下文" class="headerlink" title="5.3 函数上下文"></a>5.3 函数上下文</h2><p>在函数上下文中，我们用活动对象(activation object, AO)来表示变量对象。</p>
<p>活动对象和变量对象其实是一个东西，只是变量对象是规范上的或者说是引擎实现上的，不可在 JavaScript 环境中访问，只有到当进入一个执行上下文中，这个执行上下文的变量对象才会被激活，所以才叫 activation object 呐，而只有被激活的变量对象，也就是活动对象上的各种属性才能被访问。</p>
<p>活动对象是在进入函数上下文时刻被创建的，它通过函数的 arguments 属性初始化。arguments 属性值是 Arguments 对象。</p>
<h2 id="5-4-执行过程"><a href="#5-4-执行过程" class="headerlink" title="5.4 执行过程"></a>5.4 执行过程</h2><p>执行上下文的代码会分成两个阶段进行处理：分析和执行，我们也可以叫做：</p>
<ol>
<li>进入执行上下文</li>
<li>代码执行</li>
</ol>
<h3 id="5-4-1-进入执行上下文"><a href="#5-4-1-进入执行上下文" class="headerlink" title="5.4.1 进入执行上下文"></a>5.4.1 进入执行上下文</h3><p>当进入执行上下文时，这时候还没有执行代码，</p>
<p>变量对象会包括：</p>
<ol>
<li>函数的所有形参 (如果是函数上下文)<ul>
<li>由名称和对应值组成的一个变量对象的属性被创建</li>
<li>没有实参，属性值设为 undefined</li>
</ul>
</li>
<li>函数声明<ul>
<li>由名称和对应值（函数对象(function-object)）组成一个变量对象的属性被创建</li>
<li>如果变量对象已经存在相同名称的属性，则完全替换这个属性</li>
</ul>
</li>
<li>变量声明<ul>
<li>由名称和对应值（undefined）组成一个变量对象的属性被创建；</li>
<li>如果变量名称跟已经声明的形式参数或函数相同，则变量声明不会干扰已经存在的这类属性</li>
</ul>
</li>
</ol>
<p>举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function foo(a) &#123;</span><br><span class="line">  var b &#x3D; 2;</span><br><span class="line">  function c() &#123;&#125;</span><br><span class="line">  var d &#x3D; function() &#123;&#125;;</span><br><span class="line"></span><br><span class="line">  b &#x3D; 3;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo(1);</span><br></pre></td></tr></table></figure>

<p>在进入执行上下文后，这时候的 AO 是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">AO &#x3D; &#123;</span><br><span class="line">    arguments: &#123;</span><br><span class="line">        0: 1,</span><br><span class="line">        length: 1</span><br><span class="line">    &#125;,</span><br><span class="line">    a: 1,</span><br><span class="line">    b: undefined,</span><br><span class="line">    c: reference to function c()&#123;&#125;,</span><br><span class="line">    d: undefined</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-4-2-代码执行"><a href="#5-4-2-代码执行" class="headerlink" title="5.4.2 代码执行"></a>5.4.2 代码执行</h3><p>在代码执行阶段，会顺序执行代码，根据代码，修改变量对象的值</p>
<p>还是上面的例子，当代码执行完后，这时候的 AO 是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">AO &#x3D; &#123;</span><br><span class="line">    arguments: &#123;</span><br><span class="line">        0: 1,</span><br><span class="line">        length: 1</span><br><span class="line">    &#125;,</span><br><span class="line">    a: 1,</span><br><span class="line">    b: 3,</span><br><span class="line">    c: reference to function c()&#123;&#125;,</span><br><span class="line">    d: reference to FunctionExpression &quot;d&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>到这里变量对象的创建过程就介绍完了，让我们简洁的总结我们上述所说：</p>
<ol>
<li>全局上下文的变量对象初始化是全局对象</li>
<li>函数上下文的变量对象初始化只包括 Arguments 对象</li>
<li>在进入执行上下文时会给变量对象添加形参、函数声明、变量声明等初始的属性值</li>
<li>在代码执行阶段，会再次修改变量对象的属性值</li>
</ol>
<h2 id="5-5-思考题"><a href="#5-5-思考题" class="headerlink" title="5.5 思考题"></a>5.5 思考题</h2><p>最后让我们看几个例子：</p>
<h3 id="1-第一题"><a href="#1-第一题" class="headerlink" title="1.第一题"></a>1.第一题</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    console.log(a);</span><br><span class="line">    a &#x3D; 1;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo(); &#x2F;&#x2F; ???</span><br><span class="line"></span><br><span class="line">function bar() &#123;</span><br><span class="line">    a &#x3D; 1;</span><br><span class="line">    console.log(a);</span><br><span class="line">&#125;</span><br><span class="line">bar(); &#x2F;&#x2F; ???</span><br></pre></td></tr></table></figure>

<p>第一段会报错：<code>Uncaught ReferenceError: a is not defined</code>。</p>
<p>第二段会打印：<code>1</code>。</p>
<p>这是因为函数中的 “a” 并没有通过 var 关键字声明，所有不会被存放在 AO 中。</p>
<p>第一段执行 console 的时候， AO 的值是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">AO &#x3D; &#123;</span><br><span class="line">    arguments: &#123;</span><br><span class="line">        length: 0</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>没有 a 的值，然后就会到全局去找，全局也没有，所以会报错。</p>
<p>当第二段执行 console 的时候，全局对象已经被赋予了 a 属性，这时候就可以从全局找到 a 的值，所以会打印 1。</p>
<h3 id="2-第二题"><a href="#2-第二题" class="headerlink" title="2.第二题"></a>2.第二题</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">console.log(foo);</span><br><span class="line"></span><br><span class="line">function foo()&#123;</span><br><span class="line">    console.log(&quot;foo&quot;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var foo &#x3D; 1;</span><br></pre></td></tr></table></figure>

<p>会打印函数，而不是 undefined 。</p>
<p>这是因为在进入执行上下文时，首先会处理函数声明，其次会处理变量声明，如果如果变量名称跟已经声明的形式参数或函数相同，则变量声明不会干扰已经存在的这类属性。</p>
<h1 id="6-从ECMAScript规范解读this"><a href="#6-从ECMAScript规范解读this" class="headerlink" title="6.从ECMAScript规范解读this"></a>6.从ECMAScript规范解读this</h1><p> ECMAScript 5.1 规范地址：</p>
<p>英文版：<a target="_blank" rel="noopener" href="http://es5.github.io/#x15.1">http://es5.github.io/#x15.1</a></p>
<p>中文版：<a target="_blank" rel="noopener" href="http://yanhaijing.com/es5/#115">http://yanhaijing.com/es5/#115</a></p>
<p>让我们开始了解规范吧！</p>
<h2 id="6-1-Types"><a href="#6-1-Types" class="headerlink" title="6.1 Types"></a>6.1 Types</h2><p>首先是第 8 章 Types：</p>
<p>ECMAScript 的类型分为语言类型和规范类型。</p>
<p>ECMAScript 语言类型是开发者直接使用 ECMAScript 可以操作的。其实就是我们常说的Undefined, Null, Boolean, String, Number, 和 Object。</p>
<p>而规范类型相当于 meta-values，是用来用算法描述 ECMAScript 语言结构和 ECMAScript 语言类型的。规范类型包括：Reference, List, Completion, Property Descriptor, Property Identifier, Lexical Environment, 和 Environment Record。</p>
<p>没懂？没关系，我们只要知道在 ECMAScript 规范中还有一种只存在于规范中的类型，它们的作用是用来描述语言底层行为逻辑。</p>
<h2 id="6-2-Reference"><a href="#6-2-Reference" class="headerlink" title="6.2 Reference"></a>6.2 Reference</h2><p> Reference 类型。它与 this 的指向有着密切的关联。</p>
<p>让我们看 8.7 章 The Reference Specification Type：</p>
<blockquote>
<p>The Reference type is used to explain the behaviour of such operators as delete, typeof, and the assignment operators.</p>
</blockquote>
<p>所以 Reference 类型就是用来解释诸如 delete、typeof 以及赋值等操作行为的。</p>
<p>抄袭尤雨溪大大的话，就是：</p>
<blockquote>
<p>这里的 Reference 是一个 Specification Type，也就是 “只存在于规范里的抽象类型”。它们是为了更好地描述语言的底层行为逻辑才存在的，但并不存在于实际的 js 代码中。</p>
</blockquote>
<p>再看接下来的这段具体介绍 Reference 的内容：</p>
<blockquote>
<p>A Reference is a resolved name binding.</p>
</blockquote>
<blockquote>
<p>A Reference consists of three components, the base value, the referenced name and the Boolean valued strict reference flag.</p>
</blockquote>
<blockquote>
<p>The base value is either undefined, an Object, a Boolean, a String, a Number, or an environment record (10.2.1).</p>
</blockquote>
<blockquote>
<p>A base value of undefined indicates that the reference could not be resolved to a binding. The referenced name is a String.</p>
</blockquote>
<p>这段讲述了 Reference 的构成，由三个组成部分，分别是：</p>
<ul>
<li>base value</li>
<li>referenced name</li>
<li>strict reference</li>
</ul>
<p>可是这些到底是什么呢？</p>
<p>我们简单的理解的话：</p>
<p>base value 就是属性所在的对象或者就是 EnvironmentRecord，它的值只可能是 undefined, an Object, a Boolean, a String, a Number, or an environment record 其中的一种。</p>
<p>referenced name 就是属性的名称。</p>
<p>举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var foo &#x3D; 1;</span><br><span class="line">&#x2F;&#x2F; 对应的Reference是：</span><br><span class="line">var fooReference &#x3D; &#123;</span><br><span class="line">    base: EnvironmentRecord,</span><br><span class="line">    name: &#39;foo&#39;,</span><br><span class="line">    strict: false</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>再举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">var foo &#x3D; &#123;</span><br><span class="line">    bar: function () &#123;</span><br><span class="line">        return this;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line">foo.bar(); &#x2F;&#x2F; foo</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; bar对应的Reference是：</span><br><span class="line">var BarReference &#x3D; &#123;</span><br><span class="line">    base: foo,</span><br><span class="line">    propertyName: &#39;bar&#39;,</span><br><span class="line">    strict: false</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>而且规范中还提供了获取 Reference 组成部分的方法，比如 GetBase 和 IsPropertyReference。</p>
<p>这两个方法很简单，简单看一看：</p>
<p>1.GetBase</p>
<blockquote>
<p>GetBase(V). Returns the base value component of the reference V.</p>
</blockquote>
<p>返回 reference 的 base value。</p>
<p>2.IsPropertyReference</p>
<blockquote>
<p>IsPropertyReference(V). Returns true if either the base value is an object or HasPrimitiveBase(V) is true; otherwise returns false.</p>
</blockquote>
<p>简单的理解：如果 base value 是一个对象，就返回true。</p>
<h2 id="6-3-GetValue"><a href="#6-3-GetValue" class="headerlink" title="6.3 GetValue"></a>6.3 GetValue</h2><p>除此之外，紧接着在 8.7.1 章规范中就讲了一个用于从 Reference 类型获取对应值的方法： GetValue。</p>
<p>简单模拟 GetValue 的使用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">var foo &#x3D; 1;</span><br><span class="line"></span><br><span class="line">var fooReference &#x3D; &#123;</span><br><span class="line">    base: EnvironmentRecord,</span><br><span class="line">    name: &#39;foo&#39;,</span><br><span class="line">    strict: false</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">GetValue(fooReference) &#x2F;&#x2F; 1;</span><br></pre></td></tr></table></figure>

<p>GetValue 返回对象属性真正的值，但是要注意：</p>
<p><strong>调用 GetValue，返回的将是具体的值，而不再是一个 Reference</strong></p>
<p>这个很重要，这个很重要，这个很重要。</p>
<h2 id="6-4-如何确定this的值"><a href="#6-4-如何确定this的值" class="headerlink" title="6.4 如何确定this的值"></a>6.4 如何确定this的值</h2><p>关于 Reference 讲了那么多，为什么要讲 Reference 呢？到底 Reference 跟本文的主题 this 有哪些关联呢？如果你能耐心看完之前的内容，以下开始进入高能阶段：</p>
<p>看规范 11.2.3 Function Calls：</p>
<p>这里讲了当函数调用的时候，如何确定 this 的取值。</p>
<p>只看第一步、第六步、第七步：</p>
<blockquote>
<p>1.Let <em>ref</em> be the result of evaluating MemberExpression.</p>
</blockquote>
<blockquote>
<p>6.If Type(<em>ref</em>) is Reference, then</p>
</blockquote>
<blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a.If IsPropertyReference(ref) is true, then</span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">i.Let thisValue be GetBase(ref).</span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">b.Else, the base of ref is an Environment Record</span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">i.Let thisValue be the result of calling the ImplicitThisValue concrete method of GetBase(ref).</span><br></pre></td></tr></table></figure>

<p>7.Else, Type(<em>ref</em>) is not Reference.</p>
</blockquote>
<blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a. Let thisValue be undefined.</span><br></pre></td></tr></table></figure>
</blockquote>
<p>让我们描述一下：</p>
<p>1.计算 MemberExpression 的结果赋值给 ref</p>
<p>2.判断 ref 是不是一个 Reference 类型</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">2.1 如果 ref 是 Reference，并且 IsPropertyReference(ref) 是 true, 那么 this 的值为 GetBase(ref)</span><br><span class="line"></span><br><span class="line">2.2 如果 ref 是 Reference，并且 base value 值是 Environment Record, 那么this的值为 ImplicitThisValue(ref)</span><br><span class="line"></span><br><span class="line">2.3 如果 ref 不是 Reference，那么 this 的值为 undefined</span><br></pre></td></tr></table></figure>

<h2 id="6-5-具体分析"><a href="#6-5-具体分析" class="headerlink" title="6.5 具体分析"></a>6.5 具体分析</h2><p>让我们一步一步看：</p>
<ol>
<li>计算 MemberExpression 的结果赋值给 ref</li>
</ol>
<p>什么是 MemberExpression？看规范 11.2 Left-Hand-Side Expressions：</p>
<p>MemberExpression :</p>
<ul>
<li>PrimaryExpression // 原始表达式 可以参见《JavaScript权威指南第四章》</li>
<li>FunctionExpression // 函数定义表达式</li>
<li>MemberExpression [ Expression ] // 属性访问表达式</li>
<li>MemberExpression . IdentifierName // 属性访问表达式</li>
<li>new MemberExpression Arguments // 对象创建表达式</li>
</ul>
<p>举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    console.log(this)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo(); &#x2F;&#x2F; MemberExpression 是 foo</span><br><span class="line"></span><br><span class="line">function foo() &#123;</span><br><span class="line">    return function() &#123;</span><br><span class="line">        console.log(this)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo()(); &#x2F;&#x2F; MemberExpression 是 foo()</span><br><span class="line"></span><br><span class="line">var foo &#x3D; &#123;</span><br><span class="line">    bar: function () &#123;</span><br><span class="line">        return this;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo.bar(); &#x2F;&#x2F; MemberExpression 是 foo.bar</span><br></pre></td></tr></table></figure>

<p>所以简单理解 MemberExpression 其实就是()左边的部分。</p>
<p>2.判断 ref 是不是一个 Reference 类型。</p>
<p>关键就在于看规范是如何处理各种 MemberExpression，返回的结果是不是一个Reference类型。</p>
<p>举最后一个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">var value &#x3D; 1;</span><br><span class="line"></span><br><span class="line">var foo &#x3D; &#123;</span><br><span class="line">  value: 2,</span><br><span class="line">  bar: function () &#123;</span><br><span class="line">    return this.value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;示例1</span><br><span class="line">console.log(foo.bar());</span><br><span class="line">&#x2F;&#x2F;示例2</span><br><span class="line">console.log((foo.bar)());</span><br><span class="line">&#x2F;&#x2F;示例3</span><br><span class="line">console.log((foo.bar &#x3D; foo.bar)());</span><br><span class="line">&#x2F;&#x2F;示例4</span><br><span class="line">console.log((false || foo.bar)());</span><br><span class="line">&#x2F;&#x2F;示例5</span><br><span class="line">console.log((foo.bar, foo.bar)());</span><br></pre></td></tr></table></figure>

<h3 id="6-5-1-foo-bar"><a href="#6-5-1-foo-bar" class="headerlink" title="6.5.1 foo.bar()"></a>6.5.1 foo.bar()</h3><p>在示例 1 中，MemberExpression 计算的结果是 foo.bar，那么 foo.bar 是不是一个 Reference 呢？</p>
<p>查看规范 11.2.1 Property Accessors，这里展示了一个计算的过程，什么都不管了，就看最后一步：</p>
<blockquote>
<p>Return a value of type Reference whose base value is baseValue and whose referenced name is propertyNameString, and whose strict mode flag is strict.</p>
</blockquote>
<p>我们得知该表达式返回了一个 Reference 类型！</p>
<p>根据之前的内容，我们知道该值为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var Reference &#x3D; &#123;</span><br><span class="line">  base: foo,</span><br><span class="line">  name: &#39;bar&#39;,</span><br><span class="line">  strict: false</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>接下来按照 2.1 的判断流程走：</p>
<blockquote>
<p>2.1 如果 ref 是 Reference，并且 IsPropertyReference(ref) 是 true, 那么 this 的值为 GetBase(ref)</p>
</blockquote>
<p>该值是 Reference 类型，那么 IsPropertyReference(ref) 的结果是多少呢？</p>
<p>前面我们已经铺垫了 IsPropertyReference 方法，如果 base value 是一个对象，结果返回 true。</p>
<p>base value 为 foo，是一个对象，所以 IsPropertyReference(ref) 结果为 true。</p>
<p>这个时候我们就可以确定 this 的值了：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">this &#x3D; GetBase(ref)，</span><br></pre></td></tr></table></figure>

<p>GetBase 也已经铺垫了，获得 base value 值，这个例子中就是foo，所以 this 的值就是 foo ，示例1的结果就是 2！</p>
<p>唉呀妈呀，为了证明 this 指向foo，真是累死我了！但是知道了原理，剩下的就更快了。</p>
<h3 id="6-5-2-foo-bar"><a href="#6-5-2-foo-bar" class="headerlink" title="6.5.2 (foo.bar)()"></a>6.5.2 (foo.bar)()</h3><p>看示例2：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">console.log((foo.bar)());</span><br></pre></td></tr></table></figure>

<p>foo.bar 被 () 包住，查看规范 11.1.6 The Grouping Operator</p>
<p>直接看结果部分：</p>
<blockquote>
<p>Return the result of evaluating Expression. This may be of type Reference.</p>
</blockquote>
<blockquote>
<p>NOTE This algorithm does not apply GetValue to the result of evaluating Expression.</p>
</blockquote>
<p>实际上 () 并没有对 MemberExpression 进行计算，所以其实跟示例 1 的结果是一样的。</p>
<h3 id="6-5-3-foo-bar-foo-bar"><a href="#6-5-3-foo-bar-foo-bar" class="headerlink" title="6.5.3 (foo.bar = foo.bar)()"></a>6.5.3 (foo.bar = foo.bar)()</h3><p>看示例3，有赋值操作符，查看规范 11.13.1 Simple Assignment ( = ):</p>
<p>计算的第三步：</p>
<blockquote>
<p>3.Let rval be GetValue(rref).</p>
</blockquote>
<p>因为使用了 GetValue，所以返回的值不是 Reference 类型，</p>
<p>按照之前讲的判断逻辑：</p>
<blockquote>
<p>2.3 如果 ref 不是Reference，那么 this 的值为 undefined</p>
</blockquote>
<p>this 为 undefined，非严格模式下，this 的值为 undefined 的时候，其值会被隐式转换为全局对象。</p>
<h3 id="6-5-4-false-foo-bar"><a href="#6-5-4-false-foo-bar" class="headerlink" title="6.5.4 (false || foo.bar)()"></a>6.5.4 (false || foo.bar)()</h3><p>看示例4，逻辑与算法，查看规范 11.11 Binary Logical Operators：</p>
<p>计算第二步：</p>
<blockquote>
<p>2.Let lval be GetValue(lref).</p>
</blockquote>
<p>因为使用了 GetValue，所以返回的不是 Reference 类型，this 为 undefined</p>
<h3 id="6-5-5-foo-bar-foo-bar"><a href="#6-5-5-foo-bar-foo-bar" class="headerlink" title="6.5.5 (foo.bar, foo.bar)()"></a>6.5.5 (foo.bar, foo.bar)()</h3><p>看示例5，逗号操作符，查看规范11.14 Comma Operator ( , )</p>
<p>计算第二步：</p>
<blockquote>
<p>2.Call GetValue(lref).</p>
</blockquote>
<p>因为使用了 GetValue，所以返回的不是 Reference 类型，this 为 undefined</p>
<h3 id="6-5-6-揭晓结果"><a href="#6-5-6-揭晓结果" class="headerlink" title="6.5.6 揭晓结果"></a>6.5.6 揭晓结果</h3><p>所以最后一个例子的结果是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">var value &#x3D; 1;</span><br><span class="line"></span><br><span class="line">var foo &#x3D; &#123;</span><br><span class="line">  value: 2,</span><br><span class="line">  bar: function () &#123;</span><br><span class="line">    return this.value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;示例1</span><br><span class="line">console.log(foo.bar()); &#x2F;&#x2F; 2</span><br><span class="line">&#x2F;&#x2F;示例2</span><br><span class="line">console.log((foo.bar)()); &#x2F;&#x2F; 2</span><br><span class="line">&#x2F;&#x2F;示例3</span><br><span class="line">console.log((foo.bar &#x3D; foo.bar)()); &#x2F;&#x2F; 1</span><br><span class="line">&#x2F;&#x2F;示例4</span><br><span class="line">console.log((false || foo.bar)()); &#x2F;&#x2F; 1</span><br><span class="line">&#x2F;&#x2F;示例5</span><br><span class="line">console.log((foo.bar, foo.bar)()); &#x2F;&#x2F; 1</span><br></pre></td></tr></table></figure>

<p>注意：以上是在非严格模式下的结果，严格模式下因为 this 返回 undefined，所以示例 3 会报错。</p>
<h3 id="补充-1"><a href="#补充-1" class="headerlink" title="补充"></a>补充</h3><p>最最后，忘记了一个最最普通的情况：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    console.log(this)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo(); </span><br></pre></td></tr></table></figure>

<p>MemberExpression 是 foo，解析标识符，查看规范 10.3.1 Identifier Resolution，会返回一个 Reference 类型的值：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var fooReference &#x3D; &#123;</span><br><span class="line">    base: EnvironmentRecord,</span><br><span class="line">    name: &#39;foo&#39;,</span><br><span class="line">    strict: false</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>接下来进行判断：</p>
<blockquote>
<p>2.1 如果 ref 是 Reference，并且 IsPropertyReference(ref) 是 true, 那么 this 的值为 GetBase(ref)</p>
</blockquote>
<p>因为 base value 是 EnvironmentRecord，并不是一个 Object 类型，还记得前面讲过的 base value 的取值可能吗？ 只可能是 undefined, an Object, a Boolean, a String, a Number, 和 an environment record 中的一种。</p>
<p>IsPropertyReference(ref) 的结果为 false，进入下个判断：</p>
<blockquote>
<p>2.2 如果 ref 是 Reference，并且 base value 值是 Environment Record, 那么this的值为 ImplicitThisValue(ref)</p>
</blockquote>
<p>base value 正是 Environment Record，所以会调用 ImplicitThisValue(ref)</p>
<p>查看规范 10.2.1.1.6，ImplicitThisValue 方法的介绍：该函数始终返回 undefined。</p>
<p>所以最后 this 的值就是 undefined。</p>
<h2 id="6-6-多说一句"><a href="#6-6-多说一句" class="headerlink" title="6.6 多说一句"></a>6.6 多说一句</h2><p>尽管我们可以简单的理解 this 为调用函数的对象，如果是这样的话，如何解释下面这个例子呢？</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">var value &#x3D; 1;</span><br><span class="line"></span><br><span class="line">var foo &#x3D; &#123;</span><br><span class="line">  value: 2,</span><br><span class="line">  bar: function () &#123;</span><br><span class="line">    return this.value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">console.log((false || foo.bar)()); &#x2F;&#x2F; 1</span><br></pre></td></tr></table></figure>

<p>此外，又如何确定调用函数的对象是谁呢？在写文章之初，我就面临着这些问题，最后还是放弃从多个情形下给大家讲解 this 指向的思路，而是追根溯源的从 ECMASciript 规范讲解 this 的指向，尽管从这个角度写起来和读起来都比较吃力，但是一旦多读几遍，明白原理，绝对会给你一个全新的视角看待 this 。而你也就能明白，尽管 foo() 和 (foo.bar = foo.bar)() 最后结果都指向了 undefined，但是两者从规范的角度上却有着本质的区别。</p>
<p>此篇讲解执行上下文的 this，即便不是很理解此篇的内容，依然不影响大家了解执行上下文这个主题下其他的内容。所以，依然可以安心的看下一篇文章。</p>
<h1 id="7-立即执行函数"><a href="#7-立即执行函数" class="headerlink" title="7.立即执行函数"></a>7.立即执行函数</h1><p>可能你并没有注意到，我是一个对于专业术语有一点坚持细节人。所有，当我听到流行的但是还存在误解的术语“自执行匿名函数”多次时，我最终决定将我的想法写进这篇文章里。</p>
<p>除了提供关于这种模式事实上是如何工作的一些全面的信息，更进一步的，实际上我建议我们应该知道我们应该叫它什么。而且，如果你想跳过这里，你可以直接跳到<strong>立即调用函数表达式</strong>进行阅读，但是我建议你读完整篇文章。</p>
<h2 id="它是什么"><a href="#它是什么" class="headerlink" title="它是什么"></a>它是什么</h2><p>在 JavaScript 里，每个函数，当被调用时，都会创建一个新的执行上下文。因为在函数里定义的变量和函数是唯一在内部被访问的变量，而不是在外部被访问的变量，当调用函数时，函数提供的上下文提供了一个非常简单的方法创建私有变量。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">function makeCounter() &#123;</span><br><span class="line">    var i &#x3D; 0;</span><br><span class="line">    return function()&#123;</span><br><span class="line">        console.log(++i);</span><br><span class="line">    &#125;;   </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 记住：&#96;counter&#96;和&#96;counter2&#96;都有他们自己的变量 &#96;i&#96;</span><br><span class="line"></span><br><span class="line">var counter &#x3D; makeCounter();</span><br><span class="line">counter();&#x2F;&#x2F;1</span><br><span class="line">counter();&#x2F;&#x2F;2</span><br><span class="line"></span><br><span class="line">var counter2 &#x3D; makeCounter();</span><br><span class="line">counter2();&#x2F;&#x2F;1</span><br><span class="line">counter2();&#x2F;&#x2F;2</span><br><span class="line"></span><br><span class="line">i;&#x2F;&#x2F;ReferenceError: i is not defined(它只存在于makeCounter里)</span><br></pre></td></tr></table></figure>

<p>在许多情况下，你可能并不需要<code>makeWhatever</code>这样的函数返回多次累加值，并且可以只调用一次得到一个单一的值，在其他一些情况里，你甚至不需要明确的知道返回值。</p>
<h3 id="它的核心"><a href="#它的核心" class="headerlink" title="它的核心"></a>它的核心</h3><p>现在，无论你定义一个函数像这样<code>function foo()&#123;&#125;</code>或者<code>var foo = function()&#123;&#125;</code>，调用时，你都需要在后面加上一对圆括号，像这样<code>foo()</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;向下面这样定义的函数可以通过在函数名后加一对括号进行调用，像这样&#96;foo()&#96;，</span><br><span class="line">&#x2F;&#x2F;因为foo相对于函数表达式&#96;function()&#123;&#x2F;* code *&#x2F;&#125;&#96;只是一个引用变量</span><br><span class="line"></span><br><span class="line">var foo &#x3D; function()&#123;&#x2F;* code *&#x2F;&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;那这可以说明函数表达式可以通过在其后加上一对括号自己调用自己吗？</span><br><span class="line"></span><br><span class="line">function()&#123; &#x2F;* code *&#x2F;&#125;(); &#x2F;&#x2F;SyntaxError: Unexpected token (</span><br></pre></td></tr></table></figure>

<p>正如你所看到的，这里捕获了一个错误。当圆括号为了调用函数出现在函数后面时，无论在全局环境或者局部环境里遇到了这样的<code>function</code>关键字，默认的，它会将它当作是一个函数声明，而不是函数表达式，如果你不明确的告诉圆括号它是一个表达式，它会将其当作没有名字的函数声明并且抛出一个错误，因为函数声明需要一个名字。</p>
<p><strong>问题1：</strong>这里我么可以思考一个问题，我们是不是也可以像这样直接调用函数 <code>var foo = function()&#123;console.log(1)&#125;()</code>，答案是可以的。<br><strong>问题2：</strong>同样的，我们还可以思考一个问题，像这样的函数声明在后面加上圆括号被直接调用，又会出现什么情况呢？请看下面的解答。</p>
<h3 id="函数，圆括号，错误"><a href="#函数，圆括号，错误" class="headerlink" title="函数，圆括号，错误"></a>函数，圆括号，错误</h3><p>有趣的是，如果你为一个函数指定一个名字并在它后面放一对圆括号，同样的也会抛出错误，但这次是因为另外一个原因。当圆括号放在一个函数表达式后面指明了这是一个被调用的函数，而圆括号放在一个声明后面便意味着完全的和前面的函数声明分开了，此时圆括号只是一个简单的代表一个括号(用来控制运算优先的括号)。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;然而函数声明语法上是无效的，它仍然是一个声明，紧跟着的圆括号是无效的，因为圆括号里需要包含表达式</span><br><span class="line"></span><br><span class="line">function foo()&#123; &#x2F;* code *&#x2F; &#125;();&#x2F;&#x2F;SyntaxError: Unexpected token</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;现在，你把一个表达式放在圆括号里，没有抛出错误...,但是函数也并没有执行，因为：</span><br><span class="line"></span><br><span class="line">function foo()&#123;&#x2F;* code *&#x2F;&#125;(1)</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;它等同于如下，一个函数声明跟着一个完全没有关系的表达式:</span><br><span class="line"></span><br><span class="line">function foo()&#123;&#x2F;* code *&#x2F;&#125;</span><br><span class="line">(1);</span><br></pre></td></tr></table></figure>

<h2 id="立即执行函数表达式（IIFE）"><a href="#立即执行函数表达式（IIFE）" class="headerlink" title="立即执行函数表达式（IIFE）"></a>立即执行函数表达式（IIFE）</h2><p>幸运的是，修正语法错误很简单。最流行的也最被接受的方法是将函数声明包裹在圆括号里来告诉语法分析器去表达一个函数表达式，因为在Javascript里，圆括号不能<strong>包含</strong>声明。因为这点，当圆括号为了包裹函数碰上了 <code>function</code>关键词，它便知道将它作为一个函数表达式去解析而不是函数声明。<strong>注意理解</strong>这里的圆括号和上面的圆括号遇到函数时的表现是不一样的，也就是说。</p>
<ul>
<li>当圆括号出现在匿名函数的末尾想要调用函数时，它会默认将函数当成是函数声明。</li>
<li>当圆括号包裹函数时，它会默认将函数作为表达式去解析，而不是函数声明。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;这两种模式都可以被用来立即调用一个函数表达式，利用函数的执行来创造私有变量</span><br><span class="line"></span><br><span class="line">(function()&#123;&#x2F;* code *&#x2F;&#125;());&#x2F;&#x2F;Crockford recommends this one，括号内的表达式代表函数立即调用表达式</span><br><span class="line">(function()&#123;&#x2F;* code *&#x2F;&#125;)();&#x2F;&#x2F;But this one works just as well，括号内的表达式代表函数表达式</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; Because the point of the parens or coercing operators is to disambiguate</span><br><span class="line">&#x2F;&#x2F; between function expressions and function declarations, they can be</span><br><span class="line">&#x2F;&#x2F; omitted when the parser already expects an expression (but please see the</span><br><span class="line">&#x2F;&#x2F; &quot;important note&quot; below).</span><br><span class="line"></span><br><span class="line">var i &#x3D; function()&#123;return 10;&#125;();</span><br><span class="line">true &amp;&amp; function()&#123;&#x2F;*code*&#x2F;&#125;();</span><br><span class="line">0,function()&#123;&#125;();</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;如果你并不关心返回值，或者让你的代码尽可能的易读，你可以通过在你的函数前面带上一个一元操作符来存储字节</span><br><span class="line"></span><br><span class="line">!function()&#123;&#x2F;* code *&#x2F;&#125;();</span><br><span class="line">~function()&#123;&#x2F;* code *&#x2F;&#125;();</span><br><span class="line">-function()&#123;&#x2F;* code *&#x2F;&#125;();</span><br><span class="line">+function()&#123;&#x2F;* code *&#x2F;&#125;();</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; Here&#39;s another variation, from @kuvos - I&#39;m not sure of the performance</span><br><span class="line">&#x2F;&#x2F; implications, if any, of using the &#96;new&#96; keyword, but it works.</span><br><span class="line">&#x2F;&#x2F; http:&#x2F;&#x2F;twitter.com&#x2F;kuvos&#x2F;status&#x2F;18209252090847232</span><br><span class="line"></span><br><span class="line">new function()&#123; &#x2F;* code *&#x2F; &#125;</span><br><span class="line">new function()&#123; &#x2F;* code *&#x2F; &#125;() &#x2F;&#x2F; Only need parens if passing arguments</span><br></pre></td></tr></table></figure>

<h3 id="关于括号的重要笔记"><a href="#关于括号的重要笔记" class="headerlink" title="关于括号的重要笔记"></a>关于括号的重要笔记</h3><p>在一些情况下，当额外的带着歧义的括号围绕在函数表达式周围是没有必要的(因为这时候的括号已经将其作为一个表达式去表达)，但当括号用于调用函数表达式时，这仍然是一个好主意。</p>
<p>这样的括号指明函数表达式将会被立即调用，并且变量将会储存函数的结果，而不是函数本身。当这是一个非常长的函数表达式时，这可以节约比人阅读你代码的时间，不用滚到页面底部去看这个函数是否被调用。</p>
<p>作为规则，当你书写清楚明晰的代码时，有必要阻止 JavaScript 抛出错误的，同样也有必要阻止其他开发者对你抛出错误 <code>WTFError</code>!</p>
<h3 id="保存闭包的状态"><a href="#保存闭包的状态" class="headerlink" title="保存闭包的状态"></a>保存闭包的状态</h3><p>就像当函数通过他们的名字被调用时，参数会被传递，而当函数表达式被立即调用时，参数也会被传递。一个立即调用的函数表达式可以用来锁定值并且有效的保存此时的状态，因为任何定义在一个函数内的函数都可以使用外面函数传递进来的参数和变量(这种关系被叫做闭包)。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 它的运行原理可能并不像你想的那样，因为&#96;i&#96;的值从来没有被锁定。</span><br><span class="line">&#x2F;&#x2F; 相反的，每个链接，当被点击时（循环已经被很好的执行完毕），因此会弹出所有元素的总数，</span><br><span class="line">&#x2F;&#x2F; 因为这是 &#96;i&#96; 此时的真实值。</span><br><span class="line"></span><br><span class="line">var elems &#x3D; document.getElementsByTagName(&#39;a&#39;);</span><br><span class="line">for(var i &#x3D; 0;i &lt; elems.length; i++ ) &#123;</span><br><span class="line">    elems[i].addEventListener(&#39;click&#39;,function(e)&#123;</span><br><span class="line">        e.preventDefault();</span><br><span class="line">        alert(&#39;I am link #&#39; + i)</span><br><span class="line">        &#125;,false);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 而像下面这样改写，便可以了，因为在IIFE里，&#96;i&#96;值被锁定在了&#96;lockedInIndex&#96;里。</span><br><span class="line">&#x2F;&#x2F; 在循环结束执行时，尽管&#96;i&#96;值的数值是所有元素的总和，但每一次函数表达式被调用时，</span><br><span class="line">&#x2F;&#x2F; IIFE 里的 &#96;lockedInIndex&#96; 值都是&#96;i&#96;传给它的值,所以当链接被点击时，正确的值被弹出。</span><br><span class="line"></span><br><span class="line">var elems &#x3D; document.getElementsByTagName(&#39;a&#39;);</span><br><span class="line">for(var i &#x3D; 0;i &lt; elems.length;i++) &#123;</span><br><span class="line">    (function(lockedInIndex)&#123;</span><br><span class="line">        elems[i].addEventListener(&#39;click&#39;,function(e)&#123;</span><br><span class="line">            e.preventDefault();</span><br><span class="line">            alert(&#39;I am link #&#39; + lockedInIndex);</span><br><span class="line">            &#125;,false)</span><br><span class="line">    &#125;)(i);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;你同样可以像下面这样使用IIFE，仅仅只用括号包括点击处理函数，并不包含整个&#96;addEventListener&#96;。</span><br><span class="line">&#x2F;&#x2F;无论用哪种方式，这两个例子都可以用IIFE将值锁定，不过我发现前面一个例子更可读</span><br><span class="line"></span><br><span class="line">var elems &#x3D; document.getElementsByTagName( &#39;a&#39; );</span><br><span class="line"></span><br><span class="line">for ( var i &#x3D; 0; i &lt; elems.length; i++ ) &#123;</span><br><span class="line">    elems[ i ].addEventListener( &#39;click&#39;, (function( lockedInIndex )&#123;</span><br><span class="line">        return function(e)&#123;</span><br><span class="line">            e.preventDefault();</span><br><span class="line">            alert( &#39;I am link #&#39; + lockedInIndex );</span><br><span class="line">        &#125;;</span><br><span class="line">        &#125;)( i ),false);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>记住，在这最后两个例子里，<code>lockedInIndex</code>可以没有任何问题的访问<code>i</code>,但是作为函数的参数使用一个不同的命名标识符可以使概念更加容易的被解释。</p>
<p>立即执行函数一个最显著的优势是就算它没有命名或者说是匿名，函数表达式也可以在没有使用标识符的情况下被立即调用，一个闭包也可以在没有当前变量污染的情况下被使用。</p>
<h4 id="自执行匿名函数-“Self-executing-anonymous-function”-有什么问题呢？"><a href="#自执行匿名函数-“Self-executing-anonymous-function”-有什么问题呢？" class="headerlink" title="自执行匿名函数(“Self-executing anonymous function”)有什么问题呢？"></a>自执行匿名函数(“Self-executing anonymous function”)有什么问题呢？</h4><p>你看到它已经被提到好几次了，但是它仍然不是那么清楚的被解释，我提议将术语改成**”Immediately-Invoked Function Expression”<strong>，或者，</strong>IIFE**，如果你喜欢缩写的话。</p>
<p>什么是<strong>Immediately-Invoked Function Expression</strong>呢？它使一个被立即调用的函数表达式。就像引导你去调用的函数表达式。</p>
<p>我想Javascript社区的成员应该可以在他们的文章里或者陈述里接受术语，<strong>Immediately-Invoked Function Expression</strong>和 <strong>IIFE</strong>，因为我感觉这样更容易让这个概念被理解，并且术语”self-executing anonymous function”真的也不够精确。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;下面是个自执行函数，递归的调用自己本身</span><br><span class="line"></span><br><span class="line">function foo()&#123;foo();&#125;;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;这是一个自执行匿名函数。因为它没有标识符，它必须是使用&#96;arguments.callee&#96;属性来调用它自己</span><br><span class="line"></span><br><span class="line">var foo &#x3D; function()&#123;arguments.callee();&#125;;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;这也许算是一个自执行匿名函数，但是仅仅当&#96;foo&#96;标识符作为它的引用时，如果你将它换成用&#96;foo&#96;来调用同样可行</span><br><span class="line"></span><br><span class="line">var foo &#x3D; function()&#123;foo();&#125;;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;有些人像这样叫&#39;self-executing anonymous function&#39;下面的函数,即使它不是自执行的，因为它并没有调用它自己。然后，它只是被立即调用了而已。</span><br><span class="line"></span><br><span class="line">(function()&#123; &#x2F;*code*&#x2F; &#125;());</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;为函数表达式增加标识符(也就是说创造一个命名函数)对我们的调试会有很大帮助。一旦命名，函数将不再匿名。</span><br><span class="line"></span><br><span class="line">(function foo()&#123;&#x2F;* code *&#x2F;&#125;());</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;IIFEs同样也可以自执行，尽管，也许他不是最有用的模式</span><br><span class="line"></span><br><span class="line">(function()&#123;arguments.callee();&#125;())</span><br><span class="line">(function foo()&#123;foo();&#125;())</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; One last thing to note: this will cause an error in BlackBerry 5, because</span><br><span class="line">&#x2F;&#x2F; inside a named function expression, that name is undefined. Awesome, huh?</span><br><span class="line"></span><br><span class="line">(function foo()&#123; foo(); &#125;());</span><br></pre></td></tr></table></figure>

<p>希望上面的例子可以让你更加清楚的知道术语’self-executing’是有一些误导的，因为他并不是执行自己的函数，尽管函数已经被执行。同样的，匿名函数也没用必要特别指出，因为，<strong>Immediately Invoked Function Expression</strong>，既可以是命名函数也可以匿名函数。</p>
<h2 id="最后：模块模式"><a href="#最后：模块模式" class="headerlink" title="最后：模块模式"></a>最后：模块模式</h2><p>当我调用函数表达式时，如果我不至少一次的提醒我自己关于模块模式，我便很可能会忽略它。如果你并不属性 JavaScript 里的模块模式，它和我下面的例子很像，但是返回值用对象代替了函数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">var counter &#x3D; (function()&#123;</span><br><span class="line">    var i &#x3D; 0;</span><br><span class="line">    return &#123;</span><br><span class="line">        get: function()&#123;</span><br><span class="line">            return i;</span><br><span class="line">        &#125;,</span><br><span class="line">        set: function(val)&#123;</span><br><span class="line">            i &#x3D; val;</span><br><span class="line">        &#125;,</span><br><span class="line">        increment: function()&#123;</span><br><span class="line">            return ++i;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    &#125;());</span><br><span class="line">    counter.get();&#x2F;&#x2F;0</span><br><span class="line">    counter.set(3);</span><br><span class="line">    counter.increment();&#x2F;&#x2F;4</span><br><span class="line">    counter.increment();&#x2F;&#x2F;5</span><br><span class="line"></span><br><span class="line">    conuter.i;&#x2F;&#x2F;undefined (&#96;i&#96; is not a property of the returned object)</span><br><span class="line">    i;&#x2F;&#x2F;ReferenceError: i is not defined (it only exists inside the closure)</span><br></pre></td></tr></table></figure>

<p>模块模式方法不仅相当的厉害而且简单。非常少的代码，你可以有效的利用与方法和属性相关的命名，在一个对象里，组织全部的模块代码即最小化了全局变量的污染也创造了使用变量。</p>
<h1 id="8-instanceof-和-typeof-的实现原理"><a href="#8-instanceof-和-typeof-的实现原理" class="headerlink" title="8.instanceof 和 typeof 的实现原理"></a>8.instanceof 和 typeof 的实现原理</h1><h2 id="8-1-typeof-实现原理"><a href="#8-1-typeof-实现原理" class="headerlink" title="8.1 typeof 实现原理"></a>8.1 typeof 实现原理</h2><p><code>typeof</code> 一般被用于判断一个变量的类型，我们可以利用 <code>typeof</code> 来判断<code>number</code>,  <code>string</code>,  <code>object</code>,  <code>boolean</code>,  <code>function</code>, <code>undefined</code>,  <code>symbol</code> 这七种类型，这种判断能帮助我们搞定一些问题，比如在判断不是 object 类型的数据的时候，<code>typeof</code>能比较清楚的告诉我们具体是哪一类的类型。但是，很遗憾的一点是，<code>typeof</code> 在判断一个 object的数据的时候只能告诉我们这个数据是 object, 而不能细致的具体到是哪一种 object, 比如</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">let s &#x3D; new String(&#39;abc&#39;);</span><br><span class="line">typeof s &#x3D;&#x3D;&#x3D; &#39;object&#39;&#x2F;&#x2F; true</span><br><span class="line">s instanceof String &#x2F;&#x2F; true</span><br></pre></td></tr></table></figure>

<p>要想判断一个数据具体是哪一种 object 的时候，我们需要利用 <code>instanceof</code> 这个操作符来判断，这个我们后面会说到。</p>
<p>来谈谈关于 <code>typeof</code> 的原理吧，我们可以先想一个很有意思的问题，js 在底层是怎么存储数据的类型信息呢？或者说，一个 js 的变量，在它的底层实现中，它的类型信息是怎么实现的呢？</p>
<p>其实，js 在底层存储变量的时候，会在变量的机器码的低位1-3位存储其类型信息👉</p>
<ul>
<li>000：对象</li>
<li>010：浮点数</li>
<li>100：字符串</li>
<li>110：布尔</li>
<li>1：整数</li>
</ul>
<p>but, 对于 <code>undefined</code> 和 <code>null</code> 来说，这两个值的信息存储是有点特殊的。</p>
<p><code>null</code>：所有机器码均为0</p>
<p><code>undefined</code>：用 −2^30 整数来表示</p>
<p>所以，<code>typeof</code> 在判断 <code>null</code> 的时候就出现问题了，由于 <code>null</code> 的所有机器码均为0，因此直接被当做了对象来看待。</p>
<p>然而用 <code>instanceof</code> 来判断的话</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">null instanceof null &#x2F;&#x2F; TypeError: Right-hand side of &#39;instanceof&#39; is not an object</span><br></pre></td></tr></table></figure>

<p><code>null</code> 直接被判断为不是 object，这也是 JavaScript 的历史遗留bug，可以参考<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a>。</p>
<p>因此在用 <code>typeof</code> 来判断变量类型的时候，我们需要注意，最好是用 <code>typeof</code> 来判断基本数据类型（包括<code>symbol</code>），避免对 null 的判断。</p>
<p>还有一个不错的判断类型的方法，就是Object.prototype.toString，我们可以利用这个方法来对一个变量的类型来进行比较准确的判断</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">Object.prototype.toString.call(1) &#x2F;&#x2F; &quot;[object Number]&quot;</span><br><span class="line"></span><br><span class="line">Object.prototype.toString.call(&#39;hi&#39;) &#x2F;&#x2F; &quot;[object String]&quot;</span><br><span class="line"></span><br><span class="line">Object.prototype.toString.call(&#123;a:&#39;hi&#39;&#125;) &#x2F;&#x2F; &quot;[object Object]&quot;</span><br><span class="line"></span><br><span class="line">Object.prototype.toString.call([1,&#39;a&#39;]) &#x2F;&#x2F; &quot;[object Array]&quot;</span><br><span class="line"></span><br><span class="line">Object.prototype.toString.call(true) &#x2F;&#x2F; &quot;[object Boolean]&quot;</span><br><span class="line"></span><br><span class="line">Object.prototype.toString.call(() &#x3D;&gt; &#123;&#125;) &#x2F;&#x2F; &quot;[object Function]&quot;</span><br><span class="line"></span><br><span class="line">Object.prototype.toString.call(null) &#x2F;&#x2F; &quot;[object Null]&quot;</span><br><span class="line"></span><br><span class="line">Object.prototype.toString.call(undefined) &#x2F;&#x2F; &quot;[object Undefined]&quot;</span><br><span class="line"></span><br><span class="line">Object.prototype.toString.call(Symbol(1)) &#x2F;&#x2F; &quot;[object Symbol]&quot;</span><br></pre></td></tr></table></figure>

<h2 id="8-2-instanceof-操作符的实现原理"><a href="#8-2-instanceof-操作符的实现原理" class="headerlink" title="8.2 instanceof 操作符的实现原理"></a>8.2 instanceof 操作符的实现原理</h2><p>之前我们提到了 <code>instanceof</code> 来判断对象的具体类型，其实 <code>instanceof</code> 主要的作用就是判断一个实例是否属于某种类型</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">let person &#x3D; function () &#123;&#125;</span><br><span class="line">let nicole &#x3D; new person()</span><br><span class="line">nicole instanceof person &#x2F;&#x2F; true</span><br></pre></td></tr></table></figure>

<p>当然，<code>instanceof</code> 也可以判断一个实例是否是其父类型或者祖先类型的实例。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">let person &#x3D; function () &#123;&#125;</span><br><span class="line">let programmer &#x3D; function () &#123;&#125;</span><br><span class="line">programmer.prototype &#x3D; new person()</span><br><span class="line">let nicole &#x3D; new programmer()</span><br><span class="line">nicole instanceof person &#x2F;&#x2F; true</span><br><span class="line">nicole instanceof programmer &#x2F;&#x2F; true</span><br></pre></td></tr></table></figure>

<p>这是 <code>instanceof</code> 的用法，但是 <code>instanceof</code> 的原理是什么呢？根据 ECMAScript 语言规范，我梳理了一下大概的思路，然后整理了一段代码如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">function new_instance_of(leftVaule, rightVaule) &#123; </span><br><span class="line">    let rightProto &#x3D; rightVaule.prototype; &#x2F;&#x2F; 取右表达式的 prototype 值</span><br><span class="line">    leftVaule &#x3D; leftVaule.__proto__; &#x2F;&#x2F; 取左表达式的__proto__值</span><br><span class="line">    while (true) &#123;</span><br><span class="line">    	if (leftVaule &#x3D;&#x3D;&#x3D; null) &#123;</span><br><span class="line">            return false;	</span><br><span class="line">        &#125;</span><br><span class="line">        if (leftVaule &#x3D;&#x3D;&#x3D; rightProto) &#123;</span><br><span class="line">            return true;	</span><br><span class="line">        &#125; </span><br><span class="line">        leftVaule &#x3D; leftVaule.__proto__ </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其实 <code>instanceof</code> 主要的实现原理就是只要右边变量的 <code>prototype</code> 在左边变量的原型链上即可。因此，<code>instanceof</code> 在查找的过程中会遍历左边变量的原型链，直到找到右边变量的 <code>prototype</code>，如果查找失败，则会返回 false，告诉我们左边变量并非是右边变量的实例。</p>
<p>看几个很有趣的例子</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function Foo() &#123;&#125;</span><br><span class="line"></span><br><span class="line">Object instanceof Object &#x2F;&#x2F; true</span><br><span class="line">Function instanceof Function &#x2F;&#x2F; true</span><br><span class="line">Function instanceof Object &#x2F;&#x2F; true</span><br><span class="line">Foo instanceof Foo &#x2F;&#x2F; false</span><br><span class="line">Foo instanceof Object &#x2F;&#x2F; true</span><br><span class="line">Foo instanceof Function &#x2F;&#x2F; true</span><br></pre></td></tr></table></figure>

<p>要想全部理解 <code>instanceof</code> 的原理，除了我们刚刚提到的实现原理，我们还需要知道 JavaScript 的原型继承原理。</p>
<p>关于原型继承的原理，我简单用一张图来表示</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419203332.webp" alt="img"></p>
<p>我们知道每个 JavaScript 对象均有一个隐式的 <code>__proto__</code> 原型属性，而显式的原型属性是 <code>prototype</code>，只有 <code>Object.prototype.__proto__</code> 属性在未修改的情况下为 null 值。根据图上的原理，我们来梳理上面提到的几个有趣的 <code>instanceof</code> 使用的例子。</p>
<ul>
<li><p><code>Object instanceof Object</code></p>
<p>由图可知，Object 的 <code>prototype</code> 属性是 <code>Object.prototype</code>, 而由于 Object 本身是一个函数，由 Function 所创建，所以 <code>Object.__proto__</code> 的值是 <code>Function.prototype</code>，而 <code>Function.prototype</code> 的 <code>__proto__</code> 属性是 <code>Object.prototype</code>，所以我们可以判断出，<code>Object instanceof Object</code> 的结果是 true 。用代码简单的表示一下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">leftValue &#x3D; Object.__proto__ &#x3D; Function.prototype;</span><br><span class="line">rightValue &#x3D; Object.prototype;</span><br><span class="line">&#x2F;&#x2F; 第一次判断</span><br><span class="line">leftValue !&#x3D; rightValue</span><br><span class="line">leftValue &#x3D; Function.prototype.__proto__ &#x3D; Object.prototype</span><br><span class="line">&#x2F;&#x2F; 第二次判断</span><br><span class="line">leftValue &#x3D;&#x3D;&#x3D; rightValue</span><br><span class="line">&#x2F;&#x2F; 返回 true</span><br></pre></td></tr></table></figure>

<p><code>Function instanceof Function</code> 和 <code>Function instanceof Object</code> 的运行过程与 <code>Object instanceof Object</code> 类似，故不再详说。</p>
</li>
<li><p><code>Foo instanceof Foo</code></p>
<p>Foo 函数的 <code>prototype</code> 属性是 <code>Foo.prototype</code>，而 Foo 的 <code>__proto__</code> 属性是 <code>Function.prototype</code>，由图可知，Foo 的原型链上并没有 <code>Foo.prototype</code> ，因此 <code>Foo instanceof Foo</code> 也就返回 false 。</p>
<p>我们用代码简单的表示一下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">leftValue &#x3D; Foo, rightValue &#x3D; Foo</span><br><span class="line">leftValue &#x3D; Foo.__proto &#x3D; Function.prototype</span><br><span class="line">rightValue &#x3D; Foo.prototype</span><br><span class="line">&#x2F;&#x2F; 第一次判断</span><br><span class="line">leftValue !&#x3D; rightValue</span><br><span class="line">leftValue &#x3D; Function.prototype.__proto__ &#x3D; Object.prototype</span><br><span class="line">&#x2F;&#x2F; 第二次判断</span><br><span class="line">leftValue !&#x3D; rightValue</span><br><span class="line">leftValue &#x3D; Object.prototype &#x3D; null</span><br><span class="line">&#x2F;&#x2F; 第三次判断</span><br><span class="line">leftValue &#x3D;&#x3D;&#x3D; null</span><br><span class="line">&#x2F;&#x2F; 返回 false</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>Foo instanceof Object</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">leftValue &#x3D; Foo, rightValue &#x3D; Object</span><br><span class="line">leftValue &#x3D; Foo.__proto__ &#x3D; Function.prototype</span><br><span class="line">rightValue &#x3D; Object.prototype</span><br><span class="line">&#x2F;&#x2F; 第一次判断</span><br><span class="line">leftValue !&#x3D; rightValue</span><br><span class="line">leftValue &#x3D; Function.prototype.__proto__ &#x3D; Object.prototype</span><br><span class="line">&#x2F;&#x2F; 第二次判断</span><br><span class="line">leftValue &#x3D;&#x3D;&#x3D; rightValue</span><br><span class="line">&#x2F;&#x2F; 返回 true</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>Foo instanceof Function</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">leftValue &#x3D; Foo, rightValue &#x3D; Function</span><br><span class="line">leftValue &#x3D; Foo.__proto__ &#x3D; Function.prototype</span><br><span class="line">rightValue &#x3D; Function.prototype</span><br><span class="line">&#x2F;&#x2F; 第一次判断</span><br><span class="line">leftValue &#x3D;&#x3D;&#x3D; rightValue</span><br><span class="line">&#x2F;&#x2F; 返回 true</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="8-3-总结"><a href="#8-3-总结" class="headerlink" title="8.3 总结"></a>8.3 总结</h2><p>简单来说，我们使用 <code>typeof</code> 来判断基本数据类型是 ok 的，不过需要注意当用 <code>typeof</code> 来判断 <code>null</code> 类型时的问题，如果想要判断一个对象的具体类型可以考虑用 <code>instanceof</code>，但是 <code>instanceof</code> 也可能判断不准确，比如一个数组，他可以被 <code>instanceof</code> 判断为 Object。所以我们要想比较准确的判断对象实例的类型时，可以采取 <code>Object.prototype.toString.call</code> 方法。</p>
<h1 id="9-bind实现"><a href="#9-bind实现" class="headerlink" title="9.bind实现"></a>9.bind实现</h1><h2 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h2><p>一句话介绍 bind:</p>
<blockquote>
<p>bind() 方法会创建一个新函数。当这个新函数被调用时，bind() 的第一个参数将作为它运行时的 this，之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )</p>
</blockquote>
<p>由此我们可以首先得出 bind 函数的两个特点：</p>
<ol>
<li>返回一个函数</li>
<li>可以传入参数</li>
</ol>
<h2 id="返回函数的模拟实现"><a href="#返回函数的模拟实现" class="headerlink" title="返回函数的模拟实现"></a>返回函数的模拟实现</h2><p>从第一个特点开始，我们举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">var foo &#x3D; &#123;</span><br><span class="line">    value: 1</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">function bar() &#123;</span><br><span class="line">    console.log(this.value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 返回了一个函数</span><br><span class="line">var bindFoo &#x3D; bar.bind(foo); </span><br><span class="line"></span><br><span class="line">bindFoo(); &#x2F;&#x2F; 1</span><br></pre></td></tr></table></figure>

<p>关于指定 this 的指向，我们可以使用 call 或者 apply 实现，来写第一版的代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 第一版</span><br><span class="line">Function.prototype.bind2 &#x3D; function (context) &#123;</span><br><span class="line">    var self &#x3D; this;</span><br><span class="line">    return function () &#123;</span><br><span class="line">        return self.apply(context);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此外，之所以 <code>return self.apply(context)</code>，是考虑到绑定函数可能是有返回值的，依然是这个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">var foo &#x3D; &#123;</span><br><span class="line">    value: 1</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">function bar() &#123;</span><br><span class="line">	return this.value;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var bindFoo &#x3D; bar.bind(foo);</span><br><span class="line">console.log(bindFoo()); &#x2F;&#x2F; 1</span><br></pre></td></tr></table></figure>

<h2 id="传参的模拟实现"><a href="#传参的模拟实现" class="headerlink" title="传参的模拟实现"></a>传参的模拟实现</h2><p>接下来看第二点，可以传入参数。这个就有点让人费解了，我在 bind 的时候，是否可以传参呢？我在执行 bind 返回的函数的时候，可不可以传参呢？让我们看个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">var foo &#x3D; &#123;</span><br><span class="line">    value: 1</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">function bar(name, age) &#123;</span><br><span class="line">    console.log(this.value);</span><br><span class="line">    console.log(name);</span><br><span class="line">    console.log(age);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var bindFoo &#x3D; bar.bind(foo, &#39;daisy&#39;);</span><br><span class="line">bindFoo(&#39;18&#39;);</span><br><span class="line">&#x2F;&#x2F; 1</span><br><span class="line">&#x2F;&#x2F; daisy</span><br><span class="line">&#x2F;&#x2F; 18</span><br></pre></td></tr></table></figure>

<p>函数需要传 name 和 age 两个参数，竟然还可以在 bind 的时候，只传一个 name，在执行返回的函数的时候，再传另一个参数 age!</p>
<p>这可咋办？不急，我们用 arguments 进行处理：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 第二版</span><br><span class="line">Function.prototype.bind2 &#x3D; function (context) &#123;</span><br><span class="line"></span><br><span class="line">    var self &#x3D; this;</span><br><span class="line">    &#x2F;&#x2F; 获取bind2函数从第二个参数到最后一个参数</span><br><span class="line">    var args &#x3D; Array.prototype.slice.call(arguments, 1);</span><br><span class="line"></span><br><span class="line">    return function () &#123;</span><br><span class="line">        &#x2F;&#x2F; 这个时候的arguments是指bind返回的函数传入的参数</span><br><span class="line">        var bindArgs &#x3D; Array.prototype.slice.call(arguments);</span><br><span class="line">        return self.apply(context, args.concat(bindArgs));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="构造函数效果的模拟实现"><a href="#构造函数效果的模拟实现" class="headerlink" title="构造函数效果的模拟实现"></a>构造函数效果的模拟实现</h2><p>完成了这两点，最难的部分到啦！因为 bind 还有一个特点，就是</p>
<blockquote>
<p>一个绑定函数也能使用new操作符创建对象：这种行为就像把原函数当成构造器。提供的 this 值被忽略，同时调用时的参数被提供给模拟函数。</p>
</blockquote>
<p>也就是说当 bind 返回的函数作为构造函数的时候，bind 时指定的 this 值会失效，但传入的参数依然生效。举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">var value &#x3D; 2;</span><br><span class="line"></span><br><span class="line">var foo &#x3D; &#123;</span><br><span class="line">    value: 1</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">function bar(name, age) &#123;</span><br><span class="line">    this.habit &#x3D; &#39;shopping&#39;;</span><br><span class="line">    console.log(this.value);</span><br><span class="line">    console.log(name);</span><br><span class="line">    console.log(age);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">bar.prototype.friend &#x3D; &#39;kevin&#39;;</span><br><span class="line"></span><br><span class="line">var bindFoo &#x3D; bar.bind(foo, &#39;daisy&#39;);</span><br><span class="line"></span><br><span class="line">var obj &#x3D; new bindFoo(&#39;18&#39;);</span><br><span class="line">&#x2F;&#x2F; undefined</span><br><span class="line">&#x2F;&#x2F; daisy</span><br><span class="line">&#x2F;&#x2F; 18</span><br><span class="line">console.log(obj.habit);</span><br><span class="line">console.log(obj.friend);</span><br><span class="line">&#x2F;&#x2F; shopping</span><br><span class="line">&#x2F;&#x2F; kevin</span><br></pre></td></tr></table></figure>

<p>注意：尽管在全局和 foo 中都声明了 value 值，最后依然返回了 undefind，说明绑定的 this 失效了，如果大家了解 new 的模拟实现，就会知道这个时候的 this 已经指向了 obj。</p>
<p>所以我们可以通过修改返回的函数的原型来实现，让我们写一下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 第三版</span><br><span class="line">Function.prototype.bind2 &#x3D; function (context) &#123;</span><br><span class="line">    var self &#x3D; this;</span><br><span class="line">    var args &#x3D; Array.prototype.slice.call(arguments, 1);</span><br><span class="line"></span><br><span class="line">    var fBound &#x3D; function () &#123;</span><br><span class="line">        var bindArgs &#x3D; Array.prototype.slice.call(arguments);</span><br><span class="line">        &#x2F;&#x2F; 当作为构造函数时，this 指向实例，此时结果为 true，将绑定函数的 this 指向该实例，可以让实例获得来自绑定函数的值</span><br><span class="line">        &#x2F;&#x2F; 以上面的是 demo 为例，如果改成 &#96;this instanceof fBound ? null : context&#96;，实例只是一个空对象，将 null 改成 this ，实例会具有 habit 属性</span><br><span class="line">        &#x2F;&#x2F; 当作为普通函数时，this 指向 window，此时结果为 false，将绑定函数的 this 指向 context</span><br><span class="line">        return self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F; 修改返回函数的 prototype 为绑定函数的 prototype，实例就可以继承绑定函数的原型中的值</span><br><span class="line">    fBound.prototype &#x3D; this.prototype;</span><br><span class="line">    return fBound;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="构造函数效果的优化实现"><a href="#构造函数效果的优化实现" class="headerlink" title="构造函数效果的优化实现"></a>构造函数效果的优化实现</h2><p>但是在这个写法中，我们直接将 fBound.prototype = this.prototype，我们直接修改 fBound.prototype 的时候，也会直接修改绑定函数的 prototype。这个时候，我们可以通过一个空函数来进行中转：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 第四版</span><br><span class="line">Function.prototype.bind2 &#x3D; function (context) &#123;</span><br><span class="line"></span><br><span class="line">    var self &#x3D; this;</span><br><span class="line">    var args &#x3D; Array.prototype.slice.call(arguments, 1);</span><br><span class="line"></span><br><span class="line">    var fNOP &#x3D; function () &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    var fBound &#x3D; function () &#123;</span><br><span class="line">        var bindArgs &#x3D; Array.prototype.slice.call(arguments);</span><br><span class="line">        return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    fNOP.prototype &#x3D; this.prototype;</span><br><span class="line">    fBound.prototype &#x3D; new fNOP();</span><br><span class="line">    return fBound;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>到此为止，大的问题都已经解决，给自己一个赞！o(￣▽￣)ｄ</p>
<h2 id="三个小问题"><a href="#三个小问题" class="headerlink" title="三个小问题"></a>三个小问题</h2><p>接下来处理些小问题:</p>
<p><strong>1.apply 这段代码跟 MDN 上的稍有不同</strong></p>
<p>在 MDN 中文版讲 bind 的模拟实现时，apply 这里的代码是：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">self.apply(<span class="built_in">this</span> <span class="keyword">instanceof</span> self ? <span class="built_in">this</span> : context || <span class="built_in">this</span>, args.concat(bindArgs))</span><br></pre></td></tr></table></figure>

<p>多了一个关于 context 是否存在的判断，然而这个是错误的！</p>
<p>举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var value &#x3D; 2;</span><br><span class="line">var foo &#x3D; &#123;</span><br><span class="line">    value: 1,</span><br><span class="line">    bar: bar.bind(null)</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">function bar() &#123;</span><br><span class="line">    console.log(this.value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo.bar() &#x2F;&#x2F; 2</span><br></pre></td></tr></table></figure>

<p>以上代码正常情况下会打印 2，如果换成了 context || this，这段代码就会打印 1！</p>
<p>所以这里不应该进行 context 的判断，大家查看 MDN 同样内容的英文版，就不存在这个判断！</p>
<p><strong>2.调用 bind 的不是函数咋办？</strong></p>
<p>不行，我们要报错！</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if (typeof this !&#x3D;&#x3D; &quot;function&quot;) &#123;</span><br><span class="line">  throw new Error(&quot;Function.prototype.bind - what is trying to be bound is not callable&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>3.我要在线上用</strong></p>
<p>那别忘了做个兼容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Function.prototype.bind &#x3D; Function.prototype.bind || function () &#123;</span><br><span class="line">    ……</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>当然最好是用 <a target="_blank" rel="noopener" href="https://github.com/es-shims/es5-shim">es5-shim</a> 啦。</p>
<h2 id="最终代码"><a href="#最终代码" class="headerlink" title="最终代码"></a>最终代码</h2><p>所以最最后的代码就是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">Function.prototype.bind2 &#x3D; function (context) &#123;</span><br><span class="line"></span><br><span class="line">    if (typeof this !&#x3D;&#x3D; &quot;function&quot;) &#123;</span><br><span class="line">      throw new Error(&quot;Function.prototype.bind - what is trying to be bound is not callable&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    var self &#x3D; this;</span><br><span class="line">    var args &#x3D; Array.prototype.slice.call(arguments, 1);</span><br><span class="line"></span><br><span class="line">    var fNOP &#x3D; function () &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    var fBound &#x3D; function () &#123;</span><br><span class="line">        var bindArgs &#x3D; Array.prototype.slice.call(arguments);</span><br><span class="line">        return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    fNOP.prototype &#x3D; this.prototype;</span><br><span class="line">    fBound.prototype &#x3D; new fNOP();</span><br><span class="line">    return fBound;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="面试够用版"><a href="#面试够用版" class="headerlink" title="面试够用版"></a>面试够用版</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">Function.prototype.myBind &#x3D; function (context, ...args) &#123;</span><br><span class="line">	&#x2F;&#x2F; 环境</span><br><span class="line">    context &#x3D; context || window;</span><br><span class="line">    &#x2F;&#x2F; 创建一个Symbol变量，让当前环境指向当前位置</span><br><span class="line">    const fnSymbol &#x3D; Symbol(&quot;fn&quot;);</span><br><span class="line">    &#x2F;&#x2F; 配置环境</span><br><span class="line">    context[fnSymbol] &#x3D; this;</span><br><span class="line">	&#x2F;&#x2F; 返回闭包函数</span><br><span class="line">    return function (..._args) &#123;</span><br><span class="line">    	&#x2F;&#x2F; 与当前参数组合</span><br><span class="line">        args &#x3D; args.concat(_args);</span><br><span class="line">		&#x2F;&#x2F; 执行函数</span><br><span class="line">        context[fnSymbol](...args);</span><br><span class="line">        &#x2F;&#x2F; 避免闭包的内存泄露</span><br><span class="line">        delete context[fnSymbol];   </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="10-call和apply"><a href="#10-call和apply" class="headerlink" title="10.call和apply"></a>10.call和apply</h1><h2 id="call-和-apply-的共同点"><a href="#call-和-apply-的共同点" class="headerlink" title="call 和 apply 的共同点"></a>call 和 apply 的共同点</h2><p>它们的共同点是，都能够<strong>改变函数执行时的上下文</strong>，将一个对象的方法交给另一个对象来执行，并且是立即执行的。</p>
<p>为何要改变执行上下文？举一个生活中的小例子：平时没时间做饭的我，周末想给孩子炖个腌笃鲜尝尝。但是没有适合的锅，而我又不想出去买。所以就问邻居借了一个锅来用，这样既达到了目的，又节省了开支，一举两得。</p>
<p>改变执行上下文也是一样的，A 对象有一个方法，而 B 对象因为某种原因，也需要用到同样的方法，那么这时候我们是单独为 B 对象扩展一个方法呢，还是借用一下 A 对象的方法呢？当然是借用 A 对象的啦，既完成了需求，又减少了内存的占用。</p>
<p>另外，它们的写法也很类似，<strong>调用 call 和 apply 的对象，必须是一个函数 Function</strong>。接下来，就会说到具体的写法，那也是它们区别的主要体现。</p>
<h2 id="call-和-apply-的区别"><a href="#call-和-apply-的区别" class="headerlink" title="call 和 apply 的区别"></a>call 和 apply 的区别</h2><p>它们的区别，主要体现在参数的写法上。先来看一下它们各自的具体写法。</p>
<h4 id="call-的写法"><a href="#call-的写法" class="headerlink" title="call 的写法"></a>call 的写法</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Function.call(obj,[param1[,param2[,…[,paramN]]]])</span><br></pre></td></tr></table></figure>

<p>需要注意以下几点：</p>
<ul>
<li>调用 call 的对象，必须是个函数 Function。</li>
<li>call 的第一个参数，是一个对象。 Function 的调用者，将会指向这个对象。如果不传，则默认为全局对象 window。</li>
<li>第二个参数开始，可以接收任意个参数。每个参数会映射到相应位置的 Function 的参数上。但是如果将所有的参数作为数组传入，它们会作为一个整体映射到 Function 对应的第一个参数上，之后参数都为空。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">function func (a,b,c) &#123;&#125;</span><br><span class="line"></span><br><span class="line">func.call(obj, 1,2,3)</span><br><span class="line">&#x2F;&#x2F; func 接收到的参数实际上是 1,2,3</span><br><span class="line"></span><br><span class="line">func.call(obj, [1,2,3])</span><br><span class="line">&#x2F;&#x2F; func 接收到的参数实际上是 [1,2,3],undefined,undefined</span><br></pre></td></tr></table></figure>

<h4 id="apply-的写法"><a href="#apply-的写法" class="headerlink" title="apply 的写法"></a>apply 的写法</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Function.apply(obj[,argArray])</span><br></pre></td></tr></table></figure>

<p>需要注意的是：</p>
<ul>
<li>它的调用者必须是函数 Function，并且只接收两个参数，第一个参数的规则与 call 一致。</li>
<li>第二个参数，必须是数组或者类数组，它们会被转换成类数组，传入 Function 中，并且会被映射到 Function 对应的参数上。这也是 call 和 apply 之间，很重要的一个区别。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">func.apply(obj, [1,2,3])</span><br><span class="line">&#x2F;&#x2F; func 接收到的参数实际上是 1,2,3</span><br><span class="line"></span><br><span class="line">func.apply(obj, &#123;</span><br><span class="line">    0: 1,</span><br><span class="line">    1: 2,</span><br><span class="line">    2: 3,</span><br><span class="line">    length: 3</span><br><span class="line">&#125;)</span><br><span class="line">&#x2F;&#x2F; func 接收到的参数实际上是 1,2,3</span><br></pre></td></tr></table></figure>

<h4 id="什么是类数组？"><a href="#什么是类数组？" class="headerlink" title="什么是类数组？"></a>什么是类数组？</h4><p>先说数组，这我们都熟悉。它的特征有：可以通过角标调用，如 array[0]；具有长度属性length；可以通过 for 循环或forEach方法，进行遍历。</p>
<p>那么，类数组是什么呢？顾名思义，就是<strong>具备与数组特征类似的对象</strong>。比如，下面的这个对象，就是一个类数组。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">let arrayLike &#x3D; &#123;</span><br><span class="line">    0: 1,</span><br><span class="line">    1: 2,</span><br><span class="line">    2: 3,</span><br><span class="line">    length: 3</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>类数组 arrayLike 可以通过角标进行调用，具有length属性，同时也可以通过 for 循环进行遍历。</p>
<p>类数组，还是比较常用的，只是我们平时可能没注意到。比如，我们获取 DOM 节点的方法，返回的就是一个类数组。再比如，在一个方法中使用 arguments 获取到的所有参数，也是一个类数组。</p>
<p>但是需要注意的是：<strong>类数组无法使用 forEach、splice、push 等数组原型链上的方法</strong>，毕竟它不是真正的数组。</p>
<h2 id="call-和-apply-的用途"><a href="#call-和-apply-的用途" class="headerlink" title="call 和 apply 的用途"></a>call 和 apply 的用途</h2><p>下面会分别列举 call 和 apply 的一些使用场景。声明：例子中没有哪个场景是必须用 call 或者必须用 apply 的，只是个人习惯这么用而已。</p>
<h4 id="call-的使用场景"><a href="#call-的使用场景" class="headerlink" title="call 的使用场景"></a>call 的使用场景</h4><p><strong>1、对象的继承</strong>。如下面这个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">function superClass () &#123;</span><br><span class="line">    this.a &#x3D; 1;</span><br><span class="line">    this.print &#x3D; function () &#123;</span><br><span class="line">        console.log(this.a);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function subClass () &#123;</span><br><span class="line">    superClass.call(this);</span><br><span class="line">    this.print();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">subClass();</span><br><span class="line">&#x2F;&#x2F; 1</span><br></pre></td></tr></table></figure>

<p>subClass 通过 call 方法，继承了 superClass 的 print 方法和 a 变量。此外，subClass 还可以扩展自己的其他方法。</p>
<p><strong>2、借用方法</strong>。还记得刚才的类数组么？如果它想使用 Array 原型链上的方法，可以这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">let domNodes &#x3D; Array.prototype.slice.call(document.getElementsByTagName(&quot;*&quot;));</span><br></pre></td></tr></table></figure>

<p>这样，domNodes 就可以应用 Array 下的所有方法了。</p>
<h4 id="apply-的一些妙用"><a href="#apply-的一些妙用" class="headerlink" title="apply 的一些妙用"></a>apply 的一些妙用</h4><p><strong>1、Math.max</strong>。用它来获取数组中最大的一项。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">let max &#x3D; Math.max.apply(null, array);</span><br></pre></td></tr></table></figure>

<p>同理，要获取数组中最小的一项，可以这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">let min &#x3D; Math.min.apply(null, array);</span><br></pre></td></tr></table></figure>

<p><strong>2、实现两个数组合并</strong>。在 ES6 的扩展运算符出现之前，我们可以用 Array.prototype.push来实现。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">let arr1 &#x3D; [1, 2, 3];</span><br><span class="line">let arr2 &#x3D; [4, 5, 6];</span><br><span class="line"></span><br><span class="line">Array.prototype.push.apply(arr1, arr2);</span><br><span class="line">console.log(arr1); &#x2F;&#x2F; [1, 2, 3, 4, 5, 6]</span><br></pre></td></tr></table></figure>

<h2 id="手写apply和bind"><a href="#手写apply和bind" class="headerlink" title="手写apply和bind"></a>手写apply和bind</h2><p>call的手写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// call</span></span><br><span class="line"><span class="built_in">Function</span>.prototype.myCall = <span class="function"><span class="keyword">function</span> (<span class="params">context = <span class="built_in">window</span>, ...args</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> fn = <span class="built_in">Symbol</span>(<span class="string">&quot;fn&quot;</span>);</span><br><span class="line">  context[fn] = <span class="built_in">this</span>;</span><br><span class="line">  <span class="comment">// 重点代码，利用this指向，相当于context.caller(...args)</span></span><br><span class="line">  context[fn](...args);</span><br><span class="line">  <span class="keyword">delete</span> context[fn];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>apply的手写</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; apply</span><br><span class="line">Function.prototype.myApply &#x3D; function (context &#x3D; window, argsArr) &#123;</span><br><span class="line">  const fn &#x3D; Symbol(&quot;fn&quot;);</span><br><span class="line">  context[fn] &#x3D; this;</span><br><span class="line">  &#x2F;&#x2F; 重点代码，利用this指向，相当于context.caller(...args)</span><br><span class="line">  context[fn](...argsArr);</span><br><span class="line">  delete context[fn];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="11-函数柯里化"><a href="#11-函数柯里化" class="headerlink" title="11.函数柯里化"></a>11.函数柯里化</h1><h2 id="定义-1"><a href="#定义-1" class="headerlink" title="定义"></a>定义</h2><p>维基百科中对柯里化 (Currying) 的定义为：</p>
<blockquote>
<p>In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument.</p>
</blockquote>
<p>翻译成中文：</p>
<p>在数学和计算机科学中，柯里化是一种将使用多个参数的一个函数转换成一系列使用一个参数的函数的技术。</p>
<p>举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function add(a, b) &#123;</span><br><span class="line">    return a + b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 执行 add 函数，一次传入两个参数即可</span><br><span class="line">add(1, 2) &#x2F;&#x2F; 3</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 假设有一个 curry 函数可以做到柯里化</span><br><span class="line">var addCurry &#x3D; curry(add);</span><br><span class="line">addCurry(1)(2) &#x2F;&#x2F; 3</span><br></pre></td></tr></table></figure>

<h2 id="用途"><a href="#用途" class="headerlink" title="用途"></a>用途</h2><p>我们会讲到如何写出这个 curry 函数，并且会将这个 curry 函数写的很强大，但是在编写之前，我们需要知道柯里化到底有什么用？</p>
<p>举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 示意而已</span><br><span class="line">function ajax(type, url, data) &#123;</span><br><span class="line">    var xhr &#x3D; new XMLHttpRequest();</span><br><span class="line">    xhr.open(type, url, true);</span><br><span class="line">    xhr.send(data);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 虽然 ajax 这个函数非常通用，但在重复调用的时候参数冗余</span><br><span class="line">ajax(&#39;POST&#39;, &#39;www.test.com&#39;, &quot;name&#x3D;kevin&quot;)</span><br><span class="line">ajax(&#39;POST&#39;, &#39;www.test2.com&#39;, &quot;name&#x3D;kevin&quot;)</span><br><span class="line">ajax(&#39;POST&#39;, &#39;www.test3.com&#39;, &quot;name&#x3D;kevin&quot;)</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 利用 curry</span><br><span class="line">var ajaxCurry &#x3D; curry(ajax);</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 以 POST 类型请求数据</span><br><span class="line">var post &#x3D; ajaxCurry(&#39;POST&#39;);</span><br><span class="line">post(&#39;www.test.com&#39;, &quot;name&#x3D;kevin&quot;);</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 以 POST 类型请求来自于 www.test.com 的数据</span><br><span class="line">var postFromTest &#x3D; post(&#39;www.test.com&#39;);</span><br><span class="line">postFromTest(&quot;name&#x3D;kevin&quot;);</span><br></pre></td></tr></table></figure>

<p>想想 jQuery 虽然有 $.ajax 这样通用的方法，但是也有 $.get 和 $.post 的语法糖。</p>
<p>curry 的这种用途可以理解为：参数复用。本质上是降低通用性，提高适用性。</p>
<p>可是即便如此，是不是依然感觉没什么用呢？</p>
<p>如果我们仅仅是把参数一个一个传进去，意义可能不大，但是如果我们是把柯里化后的函数传给其他函数比如 map 呢？</p>
<p>举个例子：</p>
<p>比如我们有这样一段数据：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var person &#x3D; [&#123;name: &#39;kevin&#39;&#125;, &#123;name: &#39;daisy&#39;&#125;]</span><br></pre></td></tr></table></figure>

<p>如果我们要获取所有的 name 值，我们可以这样做：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var name &#x3D; person.map(function (item) &#123;</span><br><span class="line">    return item.name;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>不过如果我们有 curry 函数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var prop &#x3D; curry(function (key, obj) &#123;</span><br><span class="line">    return obj[key]</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">var name &#x3D; person.map(prop(&#39;name&#39;))</span><br></pre></td></tr></table></figure>

<p>我们为了获取 name 属性还要再编写一个 prop 函数，是不是又麻烦了些？</p>
<p>但是要注意，prop 函数编写一次后，以后可以多次使用，实际上代码从原本的三行精简成了一行，而且你看代码是不是更加易懂了？</p>
<p><code>person.map(prop(&#39;name&#39;))</code> 就好像直白的告诉你：person 对象遍历(map)获取(prop) name 属性。</p>
<p>是不是感觉有点意思了呢？</p>
<h2 id="第一版"><a href="#第一版" class="headerlink" title="第一版"></a>第一版</h2><p>未来我们会接触到更多有关柯里化的应用，不过那是未来的事情了，现在我们该编写这个 curry 函数了。</p>
<p>一个经常会看到的 curry 函数的实现为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 第一版</span><br><span class="line">var curry &#x3D; function (fn) &#123;</span><br><span class="line">	&#x2F;&#x2F; 保存当前参数，参数是类数组</span><br><span class="line">    var args &#x3D; [].slice.call(arguments, 1);</span><br><span class="line">    &#x2F;&#x2F; 返回闭包</span><br><span class="line">    return function() &#123;</span><br><span class="line">    	&#x2F;&#x2F; 拼接新的参数</span><br><span class="line">        var newArgs &#x3D; args.concat([].slice.call(arguments));</span><br><span class="line">        &#x2F;&#x2F; 调用函数</span><br><span class="line">        return fn.apply(this, newArgs);</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>我们可以这样使用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">function add(a, b) &#123;</span><br><span class="line">    return a + b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var addCurry &#x3D; curry(add, 1, 2);</span><br><span class="line">addCurry() &#x2F;&#x2F; 3</span><br><span class="line">&#x2F;&#x2F;或者</span><br><span class="line">var addCurry &#x3D; curry(add, 1);</span><br><span class="line">addCurry(2) &#x2F;&#x2F; 3</span><br><span class="line">&#x2F;&#x2F;或者</span><br><span class="line">var addCurry &#x3D; curry(add);</span><br><span class="line">addCurry(1, 2) &#x2F;&#x2F; 3</span><br></pre></td></tr></table></figure>

<p>已经有柯里化的感觉了，但是还没有达到要求，不过我们可以把这个函数用作辅助函数，帮助我们写真正的 curry 函数。</p>
<h2 id="第二版"><a href="#第二版" class="headerlink" title="第二版"></a>第二版</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 第二版</span><br><span class="line">function sub_curry(fn) &#123;</span><br><span class="line">    var args &#x3D; [].slice.call(arguments, 1);</span><br><span class="line">    return function() &#123;</span><br><span class="line">        return fn.apply(this, args.concat([].slice.call(arguments)));</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function curry(fn, length) &#123;</span><br><span class="line"></span><br><span class="line">    length &#x3D; length || fn.length;</span><br><span class="line"></span><br><span class="line">    var slice &#x3D; Array.prototype.slice;</span><br><span class="line"></span><br><span class="line">    return function() &#123;</span><br><span class="line">        if (arguments.length &lt; length) &#123;</span><br><span class="line">            var combined &#x3D; [fn].concat(slice.call(arguments));</span><br><span class="line">            return curry(sub_curry.apply(this, combined), length - arguments.length);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            return fn.apply(this, arguments);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们验证下这个函数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var fn &#x3D; curry(function(a, b, c) &#123;</span><br><span class="line">    return [a, b, c];</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">fn(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) &#x2F;&#x2F; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]</span><br><span class="line">fn(&quot;a&quot;, &quot;b&quot;)(&quot;c&quot;) &#x2F;&#x2F; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]</span><br><span class="line">fn(&quot;a&quot;)(&quot;b&quot;)(&quot;c&quot;) &#x2F;&#x2F; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]</span><br><span class="line">fn(&quot;a&quot;)(&quot;b&quot;, &quot;c&quot;) &#x2F;&#x2F; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]</span><br></pre></td></tr></table></figure>

<p>效果已经达到我们的预期，然而这个 curry 函数的实现好难理解呐……</p>
<p>为了让大家更好的理解这个 curry 函数，我给大家写个极简版的代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">function sub_curry(fn)&#123;</span><br><span class="line">    return function()&#123;</span><br><span class="line">        return fn()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function curry(fn, length)&#123;</span><br><span class="line">    length &#x3D; length || 4;</span><br><span class="line">    return function()&#123;</span><br><span class="line">        if (length &gt; 1) &#123;</span><br><span class="line">            return curry(sub_curry(fn), --length)</span><br><span class="line">        &#125;</span><br><span class="line">        else &#123;</span><br><span class="line">            return fn()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var fn0 &#x3D; function()&#123;</span><br><span class="line">    console.log(1)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var fn1 &#x3D; curry(fn0)</span><br><span class="line"></span><br><span class="line">fn1()()()() &#x2F;&#x2F; 1</span><br></pre></td></tr></table></figure>

<p>大家先从理解这个 curry 函数开始。</p>
<p>当执行 fn1() 时，函数返回：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">curry(sub_curry(fn0))</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">curry(function()&#123;</span><br><span class="line">    return fn0()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>当执行 fn1()() 时，函数返回：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">curry(sub_curry(function()&#123;</span><br><span class="line">    return fn0()</span><br><span class="line">&#125;))</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">curry(function()&#123;</span><br><span class="line">    return (function()&#123;</span><br><span class="line">        return fn0()</span><br><span class="line">    &#125;)()</span><br><span class="line">&#125;)</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">curry(function()&#123;</span><br><span class="line">    return fn0()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>当执行 fn1()()() 时，函数返回：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 跟 fn1()() 的分析过程一样</span><br><span class="line">curry(function()&#123;</span><br><span class="line">    return fn0()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>当执行 fn1()()()() 时，因为此时 length &gt; 2 为 false，所以执行 fn()：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">fn()</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">(function()&#123;</span><br><span class="line">    return fn0()</span><br><span class="line">&#125;)()</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">fn0()</span><br><span class="line">&#x2F;&#x2F; 执行 fn0 函数，打印 1</span><br></pre></td></tr></table></figure>

<p>再回到真正的 curry 函数，我们以下面的例子为例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var fn0 &#x3D; function(a, b, c, d) &#123;</span><br><span class="line">    return [a, b, c, d];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var fn1 &#x3D; curry(fn0);</span><br><span class="line"></span><br><span class="line">fn1(&quot;a&quot;, &quot;b&quot;)(&quot;c&quot;)(&quot;d&quot;)</span><br></pre></td></tr></table></figure>

<p>当执行 fn1(“a”, “b”) 时：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">fn1(&quot;a&quot;, &quot;b&quot;)</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">curry(fn0)(&quot;a&quot;, &quot;b&quot;)</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">curry(sub_curry(fn0, &quot;a&quot;, &quot;b&quot;))</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">&#x2F;&#x2F; 注意 ... 只是一个示意，表示该函数执行时传入的参数会作为 fn0 后面的参数传入</span><br><span class="line">curry(function(...)&#123;</span><br><span class="line">    return fn0(&quot;a&quot;, &quot;b&quot;, ...)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>当执行 fn1(“a”, “b”)(“c”) 时，函数返回：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">curry(sub_curry(function(...)&#123;</span><br><span class="line">    return fn0(&quot;a&quot;, &quot;b&quot;, ...)</span><br><span class="line">&#125;), &quot;c&quot;)</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">curry(function(...)&#123;</span><br><span class="line">    return (function(...) &#123;return fn0(&quot;a&quot;, &quot;b&quot;, ...)&#125;)(&quot;c&quot;)</span><br><span class="line">&#125;)</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">curry(function(...)&#123;</span><br><span class="line">     return fn0(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, ...)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>当执行 fn1(“a”, “b”)(“c”)(“d”) 时，此时 arguments.length &lt; length 为 false ，执行 fn(arguments)，相当于：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">(function(...)&#123;</span><br><span class="line">    return fn0(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, ...)</span><br><span class="line">&#125;)(&quot;d&quot;)</span><br><span class="line">&#x2F;&#x2F; 相当于</span><br><span class="line">fn0(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;)</span><br></pre></td></tr></table></figure>

<p>函数执行结束。</p>
<p>所以，其实整段代码又很好理解：</p>
<p>sub_curry 的作用就是用函数包裹原函数，然后给原函数传入之前的参数，当执行 fn0(…)(…) 的时候，执行包裹函数，返回原函数，然后再调用 sub_curry 再包裹原函数，然后将新的参数混合旧的参数再传入原函数，直到函数参数的数目达到要求为止。</p>
<p>如果要明白 curry 函数的运行原理，大家还是要动手写一遍，尝试着分析执行步骤。</p>
<h2 id="更易懂的实现"><a href="#更易懂的实现" class="headerlink" title="更易懂的实现"></a>更易懂的实现</h2><p>当然了，如果你觉得还是无法理解，你可以选择下面这种实现方式，可以实现同样的效果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">function curry(fn, args) &#123;</span><br><span class="line">    var length &#x3D; fn.length;</span><br><span class="line"></span><br><span class="line">    args &#x3D; args || [];</span><br><span class="line"></span><br><span class="line">    return function() &#123;</span><br><span class="line"></span><br><span class="line">        var _args &#x3D; args.slice(0),</span><br><span class="line"></span><br><span class="line">            arg, i;</span><br><span class="line"></span><br><span class="line">        for (i &#x3D; 0; i &lt; arguments.length; i++) &#123;</span><br><span class="line"></span><br><span class="line">            arg &#x3D; arguments[i];</span><br><span class="line"></span><br><span class="line">            _args.push(arg);</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">        if (_args.length &lt; length) &#123;</span><br><span class="line">            return curry.call(this, fn, _args);</span><br><span class="line">        &#125;</span><br><span class="line">        else &#123;</span><br><span class="line">            return fn.apply(this, _args);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">var fn &#x3D; curry(function(a, b, c) &#123;</span><br><span class="line">    console.log([a, b, c]);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">fn(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) &#x2F;&#x2F; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]</span><br><span class="line">fn(&quot;a&quot;, &quot;b&quot;)(&quot;c&quot;) &#x2F;&#x2F; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]</span><br><span class="line">fn(&quot;a&quot;)(&quot;b&quot;)(&quot;c&quot;) &#x2F;&#x2F; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]</span><br><span class="line">fn(&quot;a&quot;)(&quot;b&quot;, &quot;c&quot;) &#x2F;&#x2F; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]</span><br></pre></td></tr></table></figure>

<p>或许大家觉得这种方式更好理解，又能实现一样的效果，为什么不直接就讲这种呢？</p>
<p>因为想给大家介绍各种实现的方法嘛，不能因为难以理解就不给大家介绍呐~</p>
<h2 id="第三版"><a href="#第三版" class="headerlink" title="第三版"></a>第三版</h2><p>curry 函数写到这里其实已经很完善了，但是注意这个函数的传参顺序必须是从左到右，根据形参的顺序依次传入，如果我不想根据这个顺序传呢？</p>
<p>我们可以创建一个占位符，比如这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var fn &#x3D; curry(function(a, b, c) &#123;</span><br><span class="line">    console.log([a, b, c]);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">fn(&quot;a&quot;, _, &quot;c&quot;)(&quot;b&quot;) &#x2F;&#x2F; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]</span><br></pre></td></tr></table></figure>

<p>我们直接看第三版的代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 第三版</span><br><span class="line">function curry(fn, args, holes) &#123;</span><br><span class="line">    length &#x3D; fn.length;</span><br><span class="line">    args &#x3D; args || [];</span><br><span class="line">    holes &#x3D; holes || [];</span><br><span class="line">    return function() &#123;</span><br><span class="line">        var _args &#x3D; args.slice(0),</span><br><span class="line">            _holes &#x3D; holes.slice(0),</span><br><span class="line">            argsLen &#x3D; args.length,</span><br><span class="line">            holesLen &#x3D; holes.length,</span><br><span class="line">            arg, i, index &#x3D; 0;</span><br><span class="line"></span><br><span class="line">        for (i &#x3D; 0; i &lt; arguments.length; i++) &#123;</span><br><span class="line">            arg &#x3D; arguments[i];</span><br><span class="line">            &#x2F;&#x2F; 处理类似 fn(1, _, _, 4)(_, 3) 这种情况，index 需要指向 holes 正确的下标</span><br><span class="line">            if (arg &#x3D;&#x3D;&#x3D; _ &amp;&amp; holesLen) &#123;</span><br><span class="line">                index++</span><br><span class="line">                if (index &gt; holesLen) &#123;</span><br><span class="line">                    _args.push(arg);</span><br><span class="line">                    _holes.push(argsLen - 1 + index - holesLen)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            &#x2F;&#x2F; 处理类似 fn(1)(_) 这种情况</span><br><span class="line">            else if (arg &#x3D;&#x3D;&#x3D; _) &#123;</span><br><span class="line">                _args.push(arg);</span><br><span class="line">                _holes.push(argsLen + i);</span><br><span class="line">            &#125;</span><br><span class="line">            &#x2F;&#x2F; 处理类似 fn(_, 2)(1) 这种情况</span><br><span class="line">            else if (holesLen) &#123;</span><br><span class="line">                &#x2F;&#x2F; fn(_, 2)(_, 3)</span><br><span class="line">                if (index &gt;&#x3D; holesLen) &#123;</span><br><span class="line">                    _args.push(arg);</span><br><span class="line">                &#125;</span><br><span class="line">                &#x2F;&#x2F; fn(_, 2)(1) 用参数 1 替换占位符</span><br><span class="line">                else &#123;</span><br><span class="line">                    _args.splice(_holes[index], 1, arg);</span><br><span class="line">                    _holes.splice(index, 1)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            else &#123;</span><br><span class="line">                _args.push(arg);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">        if (_holes.length || _args.length &lt; length) &#123;</span><br><span class="line">            return curry.call(this, fn, _args, _holes);</span><br><span class="line">        &#125;</span><br><span class="line">        else &#123;</span><br><span class="line">            return fn.apply(this, _args);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var _ &#x3D; &#123;&#125;;</span><br><span class="line"></span><br><span class="line">var fn &#x3D; curry(function(a, b, c, d, e) &#123;</span><br><span class="line">    console.log([a, b, c, d, e]);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 验证 输出全部都是 [1, 2, 3, 4, 5]</span><br><span class="line">fn(1, 2, 3, 4, 5);</span><br><span class="line">fn(_, 2, 3, 4, 5)(1);</span><br><span class="line">fn(1, _, 3, 4, 5)(2);</span><br><span class="line">fn(1, _, 3)(_, 4)(2)(5);</span><br><span class="line">fn(1, _, _, 4)(_, 3)(2)(5);</span><br><span class="line">fn(_, 2)(_, _, 4)(1)(3)(5)</span><br></pre></td></tr></table></figure>

<h2 id="面试够用版-1"><a href="#面试够用版-1" class="headerlink" title="面试够用版"></a>面试够用版</h2><p>就是第二版</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 第一版</span><br><span class="line">var curry &#x3D; function (fn) &#123;</span><br><span class="line">	&#x2F;&#x2F; 保存当前参数，参数是类数组</span><br><span class="line">    var args &#x3D; [].slice.call(arguments, 1);</span><br><span class="line">    &#x2F;&#x2F; 返回闭包</span><br><span class="line">    return function() &#123;</span><br><span class="line">    	&#x2F;&#x2F; 拼接新的参数</span><br><span class="line">        var newArgs &#x3D; args.concat([].slice.call(arguments));</span><br><span class="line">        &#x2F;&#x2F; 调用函数</span><br><span class="line">        if (newArgs.length &lt; fn.length) &#123;</span><br><span class="line">            return curry.call(this, fn, newArgs);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            return fn.apply(this, newArgs);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="12-V8引擎的垃圾回收"><a href="#12-V8引擎的垃圾回收" class="headerlink" title="12.V8引擎的垃圾回收"></a>12.V8引擎的垃圾回收</h1><h3 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h3><p>作为目前最流行的JavaScript引擎，V8引擎从出现的那一刻起便广泛受到人们的关注，我们知道，JavaScript可以高效地运行在浏览器和Nodejs这两大宿主环境中，也是因为背后有强大的V8引擎在为其保驾护航，甚至成就了Chrome在浏览器中的霸主地位。不得不说，V8引擎为了追求极致的性能和更好的用户体验，为我们做了太多太多，从原始的<code>Full-codegen</code>和<code>Crankshaft</code>编译器升级为<code>Ignition</code>解释器和<code>TurboFan</code>编译器的强强组合，到隐藏类，内联缓存和<code>HotSpot</code>热点代码收集等一系列强有力的优化策略，V8引擎正在努力降低整体的内存占用和提升到更高的运行性能。</p>
<p>本篇主要是从V8引擎的垃圾回收机制入手，讲解一下在JavaScript代码执行的整个生命周期中V8引擎是采取怎样的垃圾回收策略来减少内存占比的，当然这部分的知识并不太影响我们写代码的流程，毕竟在一般情况下我们很少会遇到浏览器端出现内存溢出而导致程序崩溃的情况，但是至少我们对这方面有一定的了解之后，能增强我们在写代码过程中对减少内存占用，避免内存泄漏的主观意识，也许能够帮助你写出更加健壮和对V8引擎更加友好的代码。本文也是笔者在查阅资料巩固复习的过程中慢慢总结和整理出来的，若文中有错误的地方，还请指正。</p>
<h3 id="1、为何需要垃圾回收"><a href="#1、为何需要垃圾回收" class="headerlink" title="1、为何需要垃圾回收"></a>1、为何需要垃圾回收</h3><p>我们知道，在V8引擎逐行执行JavaScript代码的过程中，当遇到函数的情况时，会为其创建一个函数执行上下文(Context)环境并添加到调用堆栈的栈顶，函数的作用域(handleScope)中包含了该函数中声明的所有变量，当该函数执行完毕后，对应的执行上下文从栈顶弹出，函数的作用域会随之销毁，其包含的所有变量也会统一释放并被自动回收。试想如果在这个作用域被销毁的过程中，其中的变量不被回收，即持久占用内存，那么必然会导致内存暴增，从而引发内存泄漏导致程序的性能直线下降甚至崩溃，因此内存在使用完毕之后理当归还给操作系统以保证内存的重复利用。</p>
<blockquote>
<p>这个过程就好比你向亲戚朋友借钱，借得多了却不按时归还，那么你再下次借钱的时候肯定没有那么顺利了，或者说你的亲戚朋友不愿意再借你了，导致你的手头有点儿紧(内存泄漏，性能下降)，所以说有借有还，再借不难嘛，毕竟出来混都是要还的。</p>
</blockquote>
<p>但是JavaScript作为一门高级编程语言，并不像C语言或C++语言中需要手动地申请分配和释放内存，V8引擎已经帮我们自动进行了内存的分配和管理，好让我们有更多的精力去专注于业务层面的复杂逻辑，这对于我们前端开发人员来说是一项福利，但是随之带来的问题也是显而易见的，那就是由于不用去手动管理内存，导致写代码的过程中不够严谨从而容易引发内存泄漏(毕竟这是别人对你的好，你没有付出过，又怎能体会得到？)。</p>
<h3 id="2、V8引擎的内存限制"><a href="#2、V8引擎的内存限制" class="headerlink" title="2、V8引擎的内存限制"></a>2、V8引擎的内存限制</h3><p>虽然V8引擎帮助我们实现了自动的垃圾回收管理，解放了我们勤劳的双手，但V8引擎中的内存使用也并不是无限制的。具体来说，默认情况下，V8引擎在<code>64</code>位系统下最多只能使用约<code>1.4GB</code>的内存，在<code>32</code>位系统下最多只能使用约<code>0.7GB</code>的内存，在这样的限制下，必然会导致在node中无法直接操作大内存对象，比如将一个<code>2GB</code>大小的文件全部读入内存进行字符串分析处理，即使物理内存高达<code>32GB</code>也无法充分利用计算机的内存资源，那么为什么会有这种限制呢？这个要回到V8引擎的设计之初，起初只是作为浏览器端JavaScript的执行环境，在浏览器端我们其实很少会遇到使用大量内存的场景，因此也就没有必要将最大内存设置得过高。但这只是一方面，其实还有另外两个主要的原因：</p>
<ul>
<li><code>JS单线程机制</code>：作为浏览器的脚本语言，JS的主要用途是与用户交互以及操作DOM，那么这也决定了其作为单线程的本质，单线程意味着执行的代码必须按顺序执行，在同一时间只能处理一个任务。试想如果JS是多线程的，一个线程在删除DOM元素的同时，另一个线程对该元素进行修改操作，那么必然会导致复杂的同步问题。既然JS是单线程的，那么也就意味着在V8执行垃圾回收时，程序中的其他各种逻辑都要进入暂停等待阶段，直到垃圾回收结束后才会再次重新执行JS逻辑。因此，由于JS的单线程机制，垃圾回收的过程阻碍了主线程逻辑的执行。</li>
</ul>
<blockquote>
<p>虽然JS是单线程的，但是为了能够充分利用操作系统的多核CPU计算能力，在HTML5中引入了新的Web Worker标准，其作用就是为JS创造多线程环境，允许主线程创建Worker线程，将一些任务分配给后者运行。在主线程运行的同时，Worker在后台运行，两者互不干扰。等到Worker线程完成计算任务，再把结果返回给主线程。这样的好处是， 一些计算密集型或高延迟的任务，被Worker线程负担，主线程(通常负责UI交互)就会很流畅，不会被阻塞或者拖慢。Web Worker不是JS的一部分，而是通过JS访问的浏览器特性，其虽然创造了一个多线程的执行环境，但是子线程完全受主线程控制，不能访问浏览器特定的API，例如操作DOM，因此这个新标准并没有改变JS单线程的本质。</p>
</blockquote>
<ul>
<li><code>垃圾回收机制</code>：垃圾回收本身也是一件非常耗时的操作，假设V8的堆内存为<code>1.5G</code>，那么V8做一次小的垃圾回收需要50ms以上，而做一次非增量式回收甚至需要1s以上，可见其耗时之久，而在这1s的时间内，浏览器一直处于等待的状态，同时会失去对用户的响应，如果有动画正在运行，也会造成动画卡顿掉帧的情况，严重影响应用程序的性能。因此如果内存使用过高，那么必然会导致垃圾回收的过程缓慢，也就会导致主线程的等待时间越长，浏览器也就越长时间得不到响应。</li>
</ul>
<p>基于以上两点，V8引擎为了减少对应用的性能造成的影响，采用了一种比较粗暴的手段，那就是直接限制堆内存的大小，毕竟在浏览器端一般也不会遇到需要操作几个G内存这样的场景。但是在node端，涉及到的<code>I/O</code>操作可能会比浏览器端更加复杂多样，因此更有可能出现内存溢出的情况。不过也没关系，V8为我们提供了可配置项来让我们手动地调整内存大小，但是需要在node初始化的时候进行配置，我们可以通过如下方式来手动设置。</p>
<p>我们尝试在node命令行中输入以下命令：</p>
<blockquote>
<p>笔者本地安装的node版本为<code>v10.14.2</code>，可通过<code>node -v</code>查看本地node的版本号，不同版本可能会导致下面的命令会有所差异。</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 该命令可以用来查看node中可用的V8引擎的选项及其含义</span><br><span class="line">node --v8-options</span><br></pre></td></tr></table></figure>

<p>然后我们会在命令行窗口中看到大量关于V8的选项，这里我们暂且只关注图中红色选框中的几个选项：</p>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/7/16edeb6f141feaac?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 设置新生代内存中单个半空间的内存最小值，单位MB</span><br><span class="line">node --min-semi-space-size&#x3D;1024 xxx.js</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 设置新生代内存中单个半空间的内存最大值，单位MB</span><br><span class="line">node --max-semi-space-size&#x3D;1024 xxx.js</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 设置老生代内存最大值，单位MB</span><br><span class="line">node --max-old-space-size&#x3D;2048 xxx.js</span><br></pre></td></tr></table></figure>

<p>通过以上方法便可以手动放宽V8引擎所使用的内存限制，同时node也为我们提供了<code>process.memoryUsage()</code>方法来让我们可以查看当前node进程所占用的实际内存大小。</p>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/7/16edf18bb16af64d?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<p>在上图中，包含的几个字段的含义分别如下所示，单位均为字节：</p>
<ul>
<li><code>heapTotal</code>：表示V8当前申请到的堆内存总大小。</li>
<li><code>heapUsed</code>：表示当前内存使用量。</li>
<li><code>external</code>：表示V8内部的C++对象所占用的内存。</li>
<li><code>rss(resident set size)</code>：表示驻留集大小，是给这个node进程分配了多少物理内存，这些物理内存中包含堆，栈和代码片段。对象，闭包等存于堆内存，变量存于栈内存，实际的JavaScript源代码存于代码段内存。使用Worker线程时，<code>rss</code>将会是一个对整个进程有效的值，而其他字段则只针对当前线程。</li>
</ul>
<blockquote>
<p>在JS中声明对象时，该对象的内存就分配在堆中，如果当前已申请的堆内存已经不够分配新的对象，则会继续申请堆内存直到堆的大小超过V8的限制为止。</p>
</blockquote>
<h3 id="3、V8的垃圾回收策略"><a href="#3、V8的垃圾回收策略" class="headerlink" title="3、V8的垃圾回收策略"></a>3、V8的垃圾回收策略</h3><p>V8的垃圾回收策略主要是基于<code>分代式垃圾回收机制</code>，其根据<strong>对象的存活时间</strong>将内存的垃圾回收进行不同的分代，然后对不同的分代采用不同的垃圾回收算法。</p>
<h4 id="3-1-V8的内存结构"><a href="#3-1-V8的内存结构" class="headerlink" title="3.1 V8的内存结构"></a>3.1 V8的内存结构</h4><p>在V8引擎的堆结构组成中，其实除了<code>新生代</code>和<code>老生代</code>外，还包含其他几个部分，但是垃圾回收的过程主要出现在新生代和老生代，所以对于其他的部分我们没必要做太多的深入，有兴趣的小伙伴儿可以查阅下相关资料，V8的内存结构主要由以下几个部分组成：</p>
<ul>
<li><code>新生代(new_space)</code>：大多数的对象开始都会被分配在这里，这个区域相对较小但是垃圾回收特别频繁，该区域被分为两半，一半用来分配内存，另一半用于在垃圾回收时将需要保留的对象复制过来。</li>
<li><code>老生代(old_space)</code>：新生代中的对象在存活一段时间后就会被转移到老生代内存区，相对于新生代该内存区域的垃圾回收频率较低。老生代又分为<code>老生代指针区</code>和<code>老生代数据区</code>，前者包含大多数可能存在指向其他对象的指针的对象，后者只保存原始数据对象，这些对象没有指向其他对象的指针。</li>
<li><code>大对象区(large_object_space)</code>：存放体积超越其他区域大小的对象，每个对象都会有自己的内存，垃圾回收不会移动大对象区。</li>
<li><code>代码区(code_space)</code>：代码对象，会被分配在这里，唯一拥有执行权限的内存区域。</li>
<li><code>map区(map_space)</code>：存放Cell和Map，每个区域都是存放相同大小的元素，结构简单(这里没有做具体深入的了解，有清楚的小伙伴儿还麻烦解释下)。</li>
</ul>
<p>内存结构图如下所示：</p>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee12280b78399d?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<p>上图中的带斜纹的区域代表暂未使用的内存，新生代(new_space)被划分为了两个部分，其中一部分叫做inactive new space，表示暂未激活的内存区域，另一部分为激活状态，为什么会划分为两个部分呢，在下一小节我们会讲到。</p>
<h4 id="3-2-新生代"><a href="#3-2-新生代" class="headerlink" title="3.2 新生代"></a>3.2 新生代</h4><p>在V8引擎的内存结构中，新生代主要用于存放存活时间较短的对象。新生代内存是由两个<code>semispace(半空间)</code>构成的，内存最大值在<code>64</code>位系统和<code>32</code>位系统上分别为<code>32MB</code>和<code>16MB</code>，在新生代的垃圾回收过程中主要采用了<code>Scavenge</code>算法。</p>
<p><code>Scavenge</code>算法是一种典型的牺牲空间换取时间的算法，对于老生代内存来说，可能会存储大量对象，如果在老生代中使用这种算法，势必会造成内存资源的浪费，但是在新生代内存中，大部分对象的生命周期较短，在时间效率上表现可观，所以还是比较适合这种算法。</p>
<blockquote>
<p>在<code>Scavenge</code>算法的具体实现中，主要采用了<code>Cheney</code>算法，它将新生代内存一分为二，每一个部分的空间称为<code>semispace</code>，也就是我们在上图中看见的new_space中划分的两个区域，其中处于激活状态的区域我们称为<code>From</code>空间，未激活(inactive new space)的区域我们称为<code>To</code>空间。这两个空间中，始终只有一个处于使用状态，另一个处于闲置状态。我们的程序中声明的对象首先会被分配到<code>From</code>空间，当进行垃圾回收时，如果<code>From</code>空间中尚有存活对象，则会被复制到<code>To</code>空间进行保存，非存活的对象会被自动回收。当复制完成后，<code>From</code>空间和<code>To</code>空间完成一次角色互换，<code>To</code>空间会变为新的<code>From</code>空间，原来的<code>From</code>空间则变为<code>To</code>空间。</p>
</blockquote>
<p>基于以上算法，我们可以画出如下的流程图：</p>
<ul>
<li>假设我们在<code>From</code>空间中分配了三个对象A、B、C</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee172cf1a23c9a?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>当程序主线程任务第一次执行完毕后进入垃圾回收时，发现对象A已经没有其他引用，则表示可以对其进行回收</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee17a2fda2c461?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>对象B和对象C此时依旧处于活跃状态，因此会被复制到<code>To</code>空间中进行保存</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee17decd1d9ed2?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>接下来将<code>From</code>空间中的所有非存活对象全部清除</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee1819dd9f5999?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>此时<code>From</code>空间中的内存已经清空，开始和<code>To</code>空间完成一次角色互换</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee18439a76a3eb?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>当程序主线程在执行第二个任务时，在<code>From</code>空间中分配了一个新对象D</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee1874b4c441d2?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>任务执行完毕后再次进入垃圾回收，发现对象D已经没有其他引用，表示可以对其进行回收</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee18969e114bc7?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>对象B和对象C此时依旧处于活跃状态，再次被复制到<code>To</code>空间中进行保存</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee18cd2bff353c?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>再次将<code>From</code>空间中的所有非存活对象全部清除</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee18f4a21c517e?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li><code>From</code>空间和<code>To</code>空间继续完成一次角色互换</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee191560b716c7?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<p>通过以上的流程图，我们可以很清楚地看到，<code>Scavenge</code>算法的垃圾回收过程主要就是将存活对象在<code>From</code>空间和<code>To</code>空间之间进行复制，同时完成两个空间之间的角色互换，因此该算法的缺点也比较明显，浪费了一半的内存用于复制。</p>
<h4 id="3-3-对象晋升"><a href="#3-3-对象晋升" class="headerlink" title="3.3 对象晋升"></a>3.3 对象晋升</h4><p>当一个对象在经过多次复制之后依旧存活，那么它会被认为是一个生命周期较长的对象，在下一次进行垃圾回收时，该对象会被直接转移到老生代中，这种对象从新生代转移到老生代的过程我们称之为<code>晋升</code>。<br> 对象晋升的条件主要有以下两个：</p>
<ul>
<li>对象是否经历过一次<code>Scavenge</code>算法</li>
<li><code>To</code>空间的内存占比是否已经超过<code>25%</code></li>
</ul>
<p>默认情况下，我们创建的对象都会分配在<code>From</code>空间中，当进行垃圾回收时，在将对象从<code>From</code>空间复制到<code>To</code>空间之前，会先检查该对象的内存地址来判断是否已经经历过一次<code>Scavenge</code>算法，如果地址已经发生变动则会将该对象转移到老生代中，不会再被复制到<code>To</code>空间，可以用以下的流程图来表示：</p>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee3c5634e61f9e?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<p>如果对象没有经历过<code>Scavenge</code>算法，会被复制到<code>To</code>空间，但是如果此时<code>To</code>空间的内存占比已经超过<code>25%</code>，则该对象依旧会被转移到老生代，如下图所示:</p>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee3c90fedad146?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<p>之所以有<code>25%</code>的内存限制是因为<code>To</code>空间在经历过一次<code>Scavenge</code>算法后会和<code>From</code>空间完成角色互换，会变为<code>From</code>空间，后续的内存分配都是在<code>From</code>空间中进行的，如果内存使用过高甚至溢出，则会影响后续对象的分配，因此超过这个限制之后对象会被直接转移到老生代来进行管理。</p>
<h4 id="3-4-老生代"><a href="#3-4-老生代" class="headerlink" title="3.4 老生代"></a>3.4 老生代</h4><p>在老生代中，因为管理着大量的存活对象，如果依旧使用<code>Scavenge</code>算法的话，很明显会浪费一半的内存，因此已经不再使用<code>Scavenge</code>算法，而是采用新的算法<code>Mark-Sweep(标记清除)</code>和<code>Mark-Compact(标记整理)</code>来进行管理。</p>
<p>在早前我们可能听说过一种算法叫做<code>引用计数</code>，该算法的原理比较简单，就是看对象是否还有其他引用指向它，如果没有指向该对象的引用，则该对象会被视为垃圾并被垃圾回收器回收，示例如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 创建了两个对象obj1和obj2，其中obj2作为obj1的属性被obj1引用，因此不会被垃圾回收</span><br><span class="line">let obj1 &#x3D; &#123;</span><br><span class="line">    obj2: &#123;</span><br><span class="line">        a: 1</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 创建obj3并将obj1赋值给obj3，让两个对象指向同一个内存地址</span><br><span class="line">let obj3 &#x3D; obj1;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 将obj1重新赋值，此时原来obj1指向的对象现在只由obj3来表示</span><br><span class="line">obj1 &#x3D; null;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 创建obj4并将obj3.obj2赋值给obj4</span><br><span class="line">&#x2F;&#x2F; 此时obj2所指向的对象有两个引用：一个是作为obj3的属性，另一个是变量obj4</span><br><span class="line">let obj4 &#x3D; obj3.obj2;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 将obj3重新赋值，此时本可以对obj3指向的对象进行回收，但是因为obj3.obj2被obj4所引用，因此依旧不能被回收</span><br><span class="line">obj3 &#x3D; null;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 此时obj3.obj2已经没有指向它的引用，因此obj3指向的对象在此时可以被回收</span><br><span class="line">obj4 &#x3D; null;</span><br></pre></td></tr></table></figure>

<p>上述例子在经过一系列操作后最终对象会被垃圾回收，但是一旦我们碰到<code>循环引用</code>的场景，就会出现问题，我们看下面的例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    let a &#x3D; &#123;&#125;;</span><br><span class="line">    let b &#x3D; &#123;&#125;;</span><br><span class="line">    a.a1 &#x3D; b;</span><br><span class="line">    b.b1 &#x3D; a;</span><br><span class="line">&#125;</span><br><span class="line">foo();</span><br></pre></td></tr></table></figure>

<p>这个例子中我们将对象<code>a</code>的<code>a1</code>属性指向对象<code>b</code>，将对象<code>b</code>的<code>b1</code>属性指向对象<code>a</code>，形成两个对象相互引用，在<code>foo</code>函数执行完毕后，函数的作用域已经被销毁，作用域中包含的变量<code>a</code>和<code>b</code>本应该可以被回收，但是因为采用了<code>引用计数</code>的算法，两个变量均存在指向自身的引用，因此依旧无法被回收，导致内存泄漏。</p>
<p>因此为了避免循环引用导致的内存泄漏问题，截至2012年所有的现代浏览器均放弃了这种算法，转而采用新的<code>Mark-Sweep(标记清除)</code>和<code>Mark-Compact(标记整理)</code>算法。在上面循环引用的例子中，因为变量<code>a</code>和变量<code>b</code>无法从<code>window</code>全局对象访问到，因此无法对其进行标记，所以最终会被回收。</p>
<p><code>Mark-Sweep(标记清除)</code>分为<code>标记</code>和<code>清除</code>两个阶段，在标记阶段会遍历堆中的所有对象，然后标记活着的对象，在清除阶段中，会将死亡的对象进行清除。<code>Mark-Sweep</code>算法主要是通过判断某个对象是否可以被访问到，从而知道该对象是否应该被回收，具体步骤如下：</p>
<ul>
<li>垃圾回收器会在内部构建一个<code>根列表</code>，用于从根节点出发去寻找那些可以被访问到的变量。比如在JavaScript中，<code>window</code>全局对象可以看成一个根节点。</li>
<li>然后，垃圾回收器从所有根节点出发，遍历其可以访问到的子节点，并将其标记为活动的，根节点不能到达的地方即为非活动的，将会被视为垃圾。</li>
<li>最后，垃圾回收器将会释放所有非活动的内存块，并将其归还给操作系统。</li>
</ul>
<blockquote>
<p>以下几种情况都可以作为根节点：</p>
<ol>
<li>全局对象</li>
<li>本地函数的局部变量和参数</li>
<li>当前嵌套调用链上的其他函数的变量和参数</li>
</ol>
</blockquote>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee468e85a1084d?imageslim" alt="img"></p>
<p>但是<code>Mark-Sweep</code>算法存在一个问题，就是在经历过一次标记清除后，内存空间可能会出现不连续的状态，因为我们所清理的对象的内存地址可能不是连续的，所以就会出现内存碎片的问题，导致后面如果需要分配一个大对象而空闲内存不足以分配，就会提前触发垃圾回收，而这次垃圾回收其实是没必要的，因为我们确实有很多空闲内存，只不过是不连续的。</p>
<p>为了解决这种内存碎片的问题，<code>Mark-Compact(标记整理)</code>算法被提了出来，该算法主要就是用来解决内存的碎片化问题的，回收过程中将死亡对象清除后，在整理的过程中，会将活动的对象往堆内存的一端进行移动，移动完成后再清理掉边界外的全部内存，我们可以用如下流程图来表示：</p>
<ul>
<li>假设在老生代中有A、B、C、D四个对象</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee47d9f933bfc1?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>在垃圾回收的<code>标记</code>阶段，将对象A和对象C标记为活动的</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee486ece5fda42?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>在垃圾回收的<code>整理</code>阶段，将活动的对象往堆内存的一端移动</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee48f23fe98d7a?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<ul>
<li>在垃圾回收的<code>清除</code>阶段，将活动对象左侧的内存全部回收</li>
</ul>
<p><img data-src="https://user-gold-cdn.xitu.io/2019/12/8/16ee490a8b9bf0af?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="img"></p>
<p>至此就完成了一次老生代垃圾回收的全部过程，我们在前文中说过，由于JS的单线程机制，垃圾回收的过程会阻碍主线程同步任务的执行，待执行完垃圾回收后才会再次恢复执行主任务的逻辑，这种行为被称为<code>全停顿(stop-the-world)</code>。在标记阶段同样会阻碍主线程的执行，一般来说，老生代会保存大量存活的对象，如果在标记阶段将整个堆内存遍历一遍，那么势必会造成严重的卡顿。</p>
<p>因此，为了减少垃圾回收带来的停顿时间，V8引擎又引入了<code>Incremental Marking(增量标记)</code>的概念，即将原本需要一次性遍历堆内存的操作改为增量标记的方式，先标记堆内存中的一部分对象，然后暂停，将执行权重新交给JS主线程，待主线程任务执行完毕后再从原来暂停标记的地方继续标记，直到标记完整个堆内存。这个理念其实有点像<code>React</code>框架中的<code>Fiber</code>架构，只有在浏览器的空闲时间才会去遍历<code>Fiber Tree</code>执行对应的任务，否则延迟执行，尽可能少地影响主线程的任务，避免应用卡顿，提升应用性能。</p>
<p>得益于增量标记的好处，V8引擎后续继续引入了<code>延迟清理(lazy sweeping)</code>和<code>增量式整理(incremental compaction)</code>，让清理和整理的过程也变成增量式的。同时为了充分利用多核CPU的性能，也将引入<code>并行标记</code>和<code>并行清理</code>，进一步地减少垃圾回收对主线程的影响，为应用提升更多的性能。</p>
<h3 id="4、如何避免内存泄漏"><a href="#4、如何避免内存泄漏" class="headerlink" title="4、如何避免内存泄漏"></a>4、如何避免内存泄漏</h3><p>在我们写代码的过程中，基本上都不太会关注写出怎样的代码才能有效地避免内存泄漏，或者说浏览器和大部分的前端框架在底层已经帮助我们处理了常见的内存泄漏问题，但是我们还是有必要了解一下常见的几种避免内存泄漏的方式，毕竟在面试过程中也是经常考察的要点。</p>
<h4 id="4-1-尽可能少地创建全局变量"><a href="#4-1-尽可能少地创建全局变量" class="headerlink" title="4.1 尽可能少地创建全局变量"></a>4.1 尽可能少地创建全局变量</h4><p>在ES5中以<code>var</code>声明的方式在全局作用域中创建一个变量时，或者在函数作用域中不以任何声明的方式创建一个变量时，都会无形地挂载到<code>window</code>全局对象上，如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">var a &#x3D; 1; &#x2F;&#x2F; 等价于 window.a &#x3D; 1;</span><br><span class="line">function foo() &#123;</span><br><span class="line">    a &#x3D; 1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>等价于</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    window.a &#x3D; 1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们在<code>foo</code>函数中创建了一个变量<code>a</code>但是忘记使用<code>var</code>来声明，此时会意想不到地创建一个全局变量并挂载到window对象上，另外还有一种比较隐蔽的方式来创建全局变量：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    this.a &#x3D; 1;</span><br><span class="line">&#125;</span><br><span class="line">foo(); &#x2F;&#x2F; 相当于 window.foo()</span><br></pre></td></tr></table></figure>

<p>当<code>foo</code>函数在调用时，它所指向的运行上下文环境为<code>window</code>全局对象，因此函数中的<code>this</code>指向的其实是<code>window</code>，也就无意创建了一个全局变量。当进行垃圾回收时，在标记阶段因为<code>window</code>对象可以作为根节点，在<code>window</code>上挂载的属性均可以被访问到，并将其标记为活动的从而常驻内存，因此也就不会被垃圾回收，只有在整个进程退出时全局作用域才会被销毁。如果你遇到需要必须使用全局变量的场景，那么请保证一定要在全局变量使用完毕后将其设置为<code>null</code>从而触发回收机制。</p>
<h4 id="4-2-手动清除定时器"><a href="#4-2-手动清除定时器" class="headerlink" title="4.2 手动清除定时器"></a>4.2 手动清除定时器</h4><p>在我们的应用中经常会有使用<code>setTimeout</code>或者<code>setInterval</code>等定时器的场景，定时器本身是一个非常有用的功能，但是如果我们稍不注意，忘记在适当的时间手动清除定时器，那么很有可能就会导致内存泄漏，示例如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">const numbers &#x3D; [];</span><br><span class="line">const foo &#x3D; function() &#123;</span><br><span class="line">    for(let i &#x3D; 0;i &lt; 100000;i++) &#123;</span><br><span class="line">        numbers.push(i);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">window.setInterval(foo, 1000);</span><br></pre></td></tr></table></figure>

<p>在这个示例中，由于我们没有手动清除定时器，导致回调任务会不断地执行下去，回调中所引用的<code>numbers</code>变量也不会被垃圾回收，最终导致<code>numbers</code>数组长度无限递增，从而引发内存泄漏。</p>
<h4 id="4-3-少用闭包"><a href="#4-3-少用闭包" class="headerlink" title="4.3 少用闭包"></a>4.3 少用闭包</h4><p>闭包是JS中的一个高级特性，巧妙地利用闭包可以帮助我们实现很多高级功能。一般来说，我们在查找变量时，在本地作用域中查找不到就会沿着作用域链从内向外单向查找，但是闭包的特性可以让我们在外部作用域访问内部作用域中的变量，示例如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    let local &#x3D; 123;</span><br><span class="line">    return function() &#123;</span><br><span class="line">        return local;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">const bar &#x3D; foo();</span><br><span class="line">console.log(bar()); &#x2F;&#x2F; -&gt; 123</span><br></pre></td></tr></table></figure>

<p>在这个示例中，<code>foo</code>函数执行完毕后会返回一个匿名函数，该函数内部引用了<code>foo</code>函数中的局部变量<code>local</code>，并且通过变量<code>bar</code>来引用这个匿名的函数定义，通过这种闭包的方式我们就可以在<code>foo</code>函数的外部作用域中访问到它的局部变量<code>local</code>。一般情况下，当<code>foo</code>函数执行完毕后，它的作用域会被销毁，但是由于存在变量引用其返回的匿名函数，导致作用域无法得到释放，也就导致<code>local</code>变量无法回收，只有当我们取消掉对匿名函数的引用才会进入垃圾回收阶段。</p>
<h4 id="4-4-清除DOM引用"><a href="#4-4-清除DOM引用" class="headerlink" title="4.4 清除DOM引用"></a>4.4 清除DOM引用</h4><p>以往我们在操作DOM元素时，为了避免多次获取DOM元素，我们会将DOM元素存储在一个数据字典中，示例如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">const elements &#x3D; &#123;</span><br><span class="line">    button: document.getElementById(&#39;button&#39;)</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">function removeButton() &#123;</span><br><span class="line">    document.body.removeChild(document.getElementById(&#39;button&#39;));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在这个示例中，我们想调用<code>removeButton</code>方法来清除<code>button</code>元素，但是由于在<code>elements</code>字典中存在对<code>button</code>元素的引用，所以即使我们通过<code>removeChild</code>方法移除了<code>button</code>元素，它其实还是依旧存储在内存中无法得到释放，只有我们手动清除对<code>button</code>元素的引用才会被垃圾回收。</p>
<h4 id="4-5-弱引用"><a href="#4-5-弱引用" class="headerlink" title="4.5 弱引用"></a>4.5 弱引用</h4><p>通过前几个示例我们会发现如果我们一旦疏忽，就会容易地引发内存泄漏的问题，为此，在ES6中为我们新增了两个有效的数据结构<code>WeakMap</code>和<code>WeakSet</code>，就是为了解决内存泄漏的问题而诞生的。其表示<code>弱引用</code>，它的键名所引用的对象均是弱引用，弱引用是指垃圾回收的过程中不会将键名对该对象的引用考虑进去，只要所引用的对象没有其他的引用了，垃圾回收机制就会释放该对象所占用的内存。这也就意味着我们不需要关心<code>WeakMap</code>中键名对其他对象的引用，也不需要手动地进行引用清除，我们尝试在node中演示一下过程(参考阮一峰ES6标准入门中的示例，自己手动实现了一遍)。</p>
<p>首先打开node命令行，输入以下命令：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">node --expose-gc &#x2F;&#x2F; --expose-gc 表示允许手动执行垃圾回收机制</span><br></pre></td></tr></table></figure>

<p>然后我们执行下面的代码。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 手动执行一次垃圾回收保证内存数据准确</span><br><span class="line">&gt; global.gc();</span><br><span class="line">undefined</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 查看当前占用的内存，主要关心heapUsed字段，大小约为4.4MB</span><br><span class="line">&gt; process.memoryUsage();</span><br><span class="line">&#123; rss: 21626880,</span><br><span class="line">  heapTotal: 7585792,</span><br><span class="line">  heapUsed: 4708440,</span><br><span class="line">  external: 8710 &#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 创建一个WeakMap</span><br><span class="line">&gt; let wm &#x3D; new WeakMap();</span><br><span class="line">undefined</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 创建一个数组并赋值给变量key</span><br><span class="line">&gt; let key &#x3D; new Array(1000000);</span><br><span class="line">undefined</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 将WeakMap的键名指向该数组</span><br><span class="line">&#x2F;&#x2F; 此时该数组存在两个引用，一个是key，一个是WeakMap的键名</span><br><span class="line">&#x2F;&#x2F; 注意WeakMap是弱引用</span><br><span class="line">&gt; wm.set(key, 1);</span><br><span class="line">WeakMap &#123; [items unknown] &#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 手动执行一次垃圾回收</span><br><span class="line">&gt; global.gc();</span><br><span class="line">undefined</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 再次查看内存占用大小，heapUsed已经增加到约12MB</span><br><span class="line">&gt; process.memoryUsage();</span><br><span class="line">&#123; rss: 30232576,</span><br><span class="line">  heapTotal: 17694720,</span><br><span class="line">  heapUsed: 13068464,</span><br><span class="line">  external: 8688 &#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 手动清除变量key对数组的引用</span><br><span class="line">&#x2F;&#x2F; 注意这里并没有清除WeakMap中键名对数组的引用</span><br><span class="line">&gt; key &#x3D; null;</span><br><span class="line">null</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 再次执行垃圾回收</span><br><span class="line">&gt; global.gc()</span><br><span class="line">undefined</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 查看内存占用大小，发现heapUsed已经回到了之前的大小(这里约为4.8M，原来为4.4M，稍微有些浮动)</span><br><span class="line">&gt; process.memoryUsage();</span><br><span class="line">&#123; rss: 22110208,</span><br><span class="line">  heapTotal: 9158656,</span><br><span class="line">  heapUsed: 5089752,</span><br><span class="line">  external: 8698 &#125;</span><br></pre></td></tr></table></figure>

<p>在上述示例中，我们发现虽然我们没有手动清除<code>WeakMap</code>中的键名对数组的引用，但是内存依旧已经回到原始的大小，说明该数组已经被回收，那么这个也就是弱引用的具体含义了。</p>
<h3 id="5、总结"><a href="#5、总结" class="headerlink" title="5、总结"></a>5、总结</h3><p>本文中主要讲解了一下V8引擎的垃圾回收机制，并分别从新生代和老生代讲述了不同分代中的垃圾回收策略以及对应的回收算法，之后列出了几种常见的避免内存泄漏的方式来帮助我们写出更加优雅的代码。如果你已经了解过垃圾回收相关的内容，那么这篇文章可以帮助你简单复习加深印象，如果没有了解过，那么笔者也希望这篇文章能够帮助到你了解一些代码层面之外的底层知识点，由于V8引擎的源码是用C++实现的，所以笔者也就没有做这方面的深入了，有兴趣的小伙伴儿可以自行探究，文中有错误的地方，还希望能够在评论区指正。</p>
<h1 id="13-浮点数精度"><a href="#13-浮点数精度" class="headerlink" title="13.浮点数精度"></a>13.浮点数精度</h1><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>0.1 + 0.2 是否等于 0.3 作为一道经典的面试题，已经广外熟知，说起原因，大家能回答出这是浮点数精度问题导致，也能辩证的看待这并非是 ECMAScript 这门语言的问题，今天就是具体看一下背后的原因。</p>
<h2 id="数字类型"><a href="#数字类型" class="headerlink" title="数字类型"></a>数字类型</h2><p>ECMAScript 中的 Number 类型使用 IEEE754 标准来表示整数和浮点数值。所谓 IEEE754 标准，全称 IEEE 二进制浮点数算术标准，这个标准定义了表示浮点数的格式等内容。</p>
<p>在 IEEE754 中，规定了四种表示浮点数值的方式：单精确度（32位）、双精确度（64位）、延伸单精确度、与延伸双精确度。像 ECMAScript 采用的就是双精确度，也就是说，会用 64 位字节来储存一个浮点数。</p>
<h2 id="浮点数转二进制"><a href="#浮点数转二进制" class="headerlink" title="浮点数转二进制"></a>浮点数转二进制</h2><p>我们来看下 1020 用十进制的表示：</p>
<blockquote>
<p>1020 = <strong>1</strong> * 10^3 + <strong>0</strong> * 10^2 + <strong>2</strong> * 10^1 + <strong>0</strong> * 10^0</p>
</blockquote>
<p>所以 1020 用十进制表示就是 1020……(哈哈)</p>
<p>如果 1020 用二进制来表示呢？</p>
<blockquote>
<p>1020 = <strong>1</strong> * 2^9 + <strong>1</strong> * 2^8 + <strong>1</strong> * 2^7 + <strong>1</strong> * 2^6 + <strong>1</strong> * 2^5 + <strong>1</strong> * 2^4 + <strong>1</strong> * 2^3 + <strong>1</strong> * 2^2 + <strong>0</strong> * 2^1 + <strong>0</strong> * 2^0</p>
</blockquote>
<p>所以 1020 的二进制为 <code>1111111100</code></p>
<p>那如果是 0.75 用二进制表示呢？同理应该是：</p>
<blockquote>
<p>0.75 = a * 2^-1 + b * 2^-2 + c * 2^-3 + d * 2^-4 + …</p>
</blockquote>
<p>因为使用的是二进制，这里的 abcd……的值的要么是 0 要么是 1。</p>
<p>那怎么算出 abcd…… 的值呢，我们可以两边不停的乘以 2 算出来，解法如下：</p>
<blockquote>
<p>0.75 = a * 2^-1 + b * 2^-2 + c * 2^-3 + d * 2^-4…</p>
</blockquote>
<p>两边同时乘以 2</p>
<blockquote>
<p>1 + 0.5 = a * 2^0 + b * 2^-1 + c * 2^-2 + d * 2^-3… (所以 a = 1)</p>
</blockquote>
<p>剩下的：</p>
<blockquote>
<p>0.5 = b * 2^-1 + c * 2^-2 + d * 2^-3…</p>
</blockquote>
<p>再同时乘以 2</p>
<blockquote>
<p>1 + 0 = b * 2^0 + c * 2^-2 + d * 2^-3… (所以 b = 1)</p>
</blockquote>
<p>所以 0.75 用二进制表示就是 0.ab，也就是 0.11</p>
<p>然而不是所有的数都像 0.75 这么好算，我们来算下 0.1：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">0.1 &#x3D; a * 2^-1 + b * 2^-2 + c * 2^-3 + d * 2^-4 + ...</span><br><span class="line"></span><br><span class="line">0 + 0.2 &#x3D; a * 2^0 + b * 2^-1 + c * 2^-2 + ...   (a &#x3D; 0)</span><br><span class="line">0 + 0.4 &#x3D; b * 2^0 + c * 2^-1 + d * 2^-2 + ...   (b &#x3D; 0)</span><br><span class="line">0 + 0.8 &#x3D; c * 2^0 + d * 2^-1 + e * 2^-2 + ...   (c &#x3D; 0)</span><br><span class="line">1 + 0.6 &#x3D; d * 2^0 + e * 2^-1 + f * 2^-2 + ...   (d &#x3D; 1)</span><br><span class="line">1 + 0.2 &#x3D; e * 2^0 + f * 2^-1 + g * 2^-2 + ...   (e &#x3D; 1)</span><br><span class="line">0 + 0.4 &#x3D; f * 2^0 + g * 2^-1 + h * 2^-2 + ...   (f &#x3D; 0)</span><br><span class="line">0 + 0.8 &#x3D; g * 2^0 + h * 2^-1 + i * 2^-2 + ...   (g &#x3D; 0)</span><br><span class="line">1 + 0.6 &#x3D; h * 2^0 + i * 2^-1 + j * 2^-2 + ...   (h &#x3D; 1)</span><br><span class="line">....</span><br></pre></td></tr></table></figure>

<p>然后你就会发现，这个计算在不停的循环，所以 0.1 用二进制表示就是 0.00011001100110011……</p>
<h2 id="浮点数的存储"><a href="#浮点数的存储" class="headerlink" title="浮点数的存储"></a>浮点数的存储</h2><p>虽然 0.1 转成二进制时是一个无限循环的数，但计算机总要储存吧，我们知道 ECMAScript 使用 64 位字节来储存一个浮点数，那具体是怎么储存的呢？这就要说回 IEEE754 这个标准了，毕竟是这个标准规定了存储的方式。</p>
<p>这个标准认为，一个浮点数 (Value) 可以这样表示：</p>
<blockquote>
<p>Value = sign * exponent * fraction</p>
</blockquote>
<p>看起来很抽象的样子，简单理解就是科学计数法……</p>
<p>比如 -1020，用科学计数法表示就是:</p>
<blockquote>
<p>-1 * 10^3 * 1.02</p>
</blockquote>
<p>sign 就是 -1，exponent 就是 10^3，fraction 就是 1.02</p>
<p>对于二进制也是一样，以 0.1 的二进制 0.00011001100110011…… 这个数来说：</p>
<p>可以表示为：</p>
<blockquote>
<p>1 * 2^-4 * 1.1001100110011……</p>
</blockquote>
<p>其中 sign 就是 1，exponent 就是 2^-4，fraction 就是 1.1001100110011……</p>
<p>而当只做二进制科学计数法的表示时，这个 Value 的表示可以再具体一点变成：</p>
<blockquote>
<p>V = (-1)^S * (1 + Fraction) * 2^E</p>
</blockquote>
<p>(如果所有的浮点数都可以这样表示，那么我们存储的时候就把这其中会变化的一些值存储起来就好了)</p>
<p>我们来一点点看：</p>
<p><code>(-1)^S</code> 表示符号位，当 S = 0，V 为正数；当 S = 1，V 为负数。</p>
<p>再看 <code>(1 + Fraction)</code>，这是因为所有的浮点数都可以表示为 1.xxxx * 2^xxx 的形式，前面的一定是 1.xxx，那干脆我们就不存储这个 1 了，直接存后面的 xxxxx 好了，这也就是 Fraction 的部分。</p>
<p>最后再看 <code>2^E</code></p>
<p>如果是 1020.75，对应二进制数就是 1111111100.11，对应二进制科学计数法就是 1 * 1.11111110011 * 2^9，E 的值就是 9，而如果是 0.1 ，对应二进制是 1 * 1.1001100110011…… * 2^-4， E 的值就是 -4，也就是说，E 既可能是负数，又可能是正数，那问题就来了，那我们该怎么储存这个 E 呢？</p>
<p>我们这样解决，假如我们用 8 位字节来存储 E 这个数，如果只有正数的话，储存的值的范围是 0 ~ 254，而如果要储存正负数的话，值的范围就是 -127~127，我们在存储的时候，把要存储的数字加上 127，这样当我们存 -127 的时候，我们存 0，当存 127 的时候，存 254，这样就解决了存负数的问题。对应的，当取值的时候，我们再减去 127。</p>
<p>所以呢，真到实际存储的时候，我们并不会直接存储 E，而是会存储 E + bias，当用 8 个字节的时候，这个 bias 就是 127。</p>
<p>所以，如果要存储一个浮点数，我们存 S 和 Fraction 和 E + bias 这三个值就好了，那具体要分配多少个字节位来存储这些数呢？IEEE754 给出了标准：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144326.jpeg" alt="IEEE754"></p>
<p>在这个标准下：</p>
<p>我们会用 1 位存储 S，0 表示正数，1 表示负数。</p>
<p>用 11 位存储 E + bias，对于 11 位来说，bias 的值是 2^(11-1) - 1，也就是 1023。</p>
<p>用 52 位存储 Fraction。</p>
<p>举个例子，就拿 0.1 来看，对应二进制是 1 * 1.1001100110011…… * 2^-4， Sign 是 0，E + bias 是 -4 + 1023 = 1019，1019 用二进制表示是 1111111011，Fraction 是 1001100110011……</p>
<p>对应 64 个字节位的完整表示就是：</p>
<blockquote>
<p>0 01111111011 1001100110011001100110011001100110011001100110011010</p>
</blockquote>
<p>同理, 0.2 表示的完整表示是：</p>
<blockquote>
<p>0 01111111100 1001100110011001100110011001100110011001100110011010</p>
</blockquote>
<p>所以当 0.1 存下来的时候，就已经发生了精度丢失，当我们用浮点数进行运算的时候，使用的其实是精度丢失后的数。</p>
<h2 id="浮点数的运算"><a href="#浮点数的运算" class="headerlink" title="浮点数的运算"></a>浮点数的运算</h2><p>关于浮点数的运算，一般由以下五个步骤完成：对阶、尾数运算、规格化、舍入处理、溢出判断。我们来简单看一下 0.1 和 0.2 的计算。</p>
<p>首先是对阶，所谓对阶，就是把阶码调整为相同，比如 0.1 是 <code>1.1001100110011…… * 2^-4</code>，阶码是 -4，而 0.2 就是 <code>1.10011001100110...* 2^-3</code>，阶码是 -3，两个阶码不同，所以先调整为相同的阶码再进行计算，调整原则是小阶对大阶，也就是 0.1 的 -4 调整为 -3，对应变成 <code>0.11001100110011…… * 2^-3</code></p>
<p>接下来是尾数计算:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">  0.1100110011001100110011001100110011001100110011001101</span><br><span class="line">+ 1.1001100110011001100110011001100110011001100110011010</span><br><span class="line">————————————————————————————————————————————————————————</span><br><span class="line"> 10.0110011001100110011001100110011001100110011001100111</span><br></pre></td></tr></table></figure>

<p>我们得到结果为 <code>10.0110011001100110011001100110011001100110011001100111 * 2^-3</code></p>
<p>将这个结果处理一下，即结果规格化，变成 <code>1.0011001100110011001100110011001100110011001100110011(1) * 2^-2</code></p>
<p>括号里的 1 意思是说计算后这个 1 超出了范围，所以要被舍弃了。</p>
<p>再然后是舍入，四舍五入对应到二进制中，就是 0 舍 1 入，因为我们要把括号里的 1 丢了，所以这里会进一，结果变成</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1.0011001100110011001100110011001100110011001100110100 * 2^-2</span><br></pre></td></tr></table></figure>

<p>本来还有一个溢出判断，因为这里不涉及，就不讲了。</p>
<p>所以最终的结果存成 64 位就是</p>
<blockquote>
<p>0 01111111101 0011001100110011001100110011001100110011001100110100</p>
</blockquote>
<p>将它转换为10进制数就得到 <code>0.30000000000000004440892098500626</code></p>
<p>因为两次存储时的精度丢失加上一次运算时的精度丢失，最终导致了 0.1 + 0.2 !== 0.3</p>
<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 十进制转二进制</span><br><span class="line">parseFloat(0.1).toString(2);</span><br><span class="line">&#x3D;&gt; &quot;0.0001100110011001100110011001100110011001100110011001101&quot;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 二进制转十进制</span><br><span class="line">parseInt(1100100,2)</span><br><span class="line">&#x3D;&gt; 100</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 以指定的精度返回该数值对象的字符串表示</span><br><span class="line">(0.1 + 0.2).toPrecision(21)</span><br><span class="line">&#x3D;&gt; &quot;0.300000000000000044409&quot;</span><br><span class="line">(0.3).toPrecision(21)</span><br><span class="line">&#x3D;&gt; &quot;0.299999999999999988898&quot;</span><br></pre></td></tr></table></figure>



<h1 id="14-new"><a href="#14-new" class="headerlink" title="14.new"></a>14.new</h1><h2 id="定义-2"><a href="#定义-2" class="headerlink" title="定义"></a>定义</h2><p>一句话介绍 new:</p>
<blockquote>
<p>new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象类型之一</p>
</blockquote>
<p>也许有点难懂，我们在模拟 new 之前，先看看 new 实现了哪些功能。</p>
<p>举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; Otaku 御宅族，简称宅</span><br><span class="line">function Otaku (name, age) &#123;</span><br><span class="line">    this.name &#x3D; name;</span><br><span class="line">    this.age &#x3D; age;</span><br><span class="line"></span><br><span class="line">    this.habit &#x3D; &#39;Games&#39;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 因为缺乏锻炼的缘故，身体强度让人担忧</span><br><span class="line">Otaku.prototype.strength &#x3D; 60;</span><br><span class="line"></span><br><span class="line">Otaku.prototype.sayYourName &#x3D; function () &#123;</span><br><span class="line">    console.log(&#39;I am &#39; + this.name);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var person &#x3D; new Otaku(&#39;Kevin&#39;, &#39;18&#39;);</span><br><span class="line"></span><br><span class="line">console.log(person.name) &#x2F;&#x2F; Kevin</span><br><span class="line">console.log(person.habit) &#x2F;&#x2F; Games</span><br><span class="line">console.log(person.strength) &#x2F;&#x2F; 60</span><br><span class="line"></span><br><span class="line">person.sayYourName(); &#x2F;&#x2F; I am Kevin</span><br></pre></td></tr></table></figure>

<p>从这个例子中，我们可以看到，实例 person 可以：</p>
<ol>
<li>访问到 Otaku 构造函数里的属性</li>
<li>访问到 Otaku.prototype 中的属性</li>
</ol>
<p>接下来，我们可以尝试着模拟一下了。</p>
<p>因为 new 是关键字，所以无法像 bind 函数一样直接覆盖，所以我们写一个函数，命名为 objectFactory，来模拟 new 的效果。用的时候是这样的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function Otaku () &#123;</span><br><span class="line">    ……</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 使用 new</span><br><span class="line">var person &#x3D; new Otaku(……);</span><br><span class="line">&#x2F;&#x2F; 使用 objectFactory</span><br><span class="line">var person &#x3D; objectFactory(Otaku, ……)</span><br></pre></td></tr></table></figure>

<h2 id="初步实现"><a href="#初步实现" class="headerlink" title="初步实现"></a>初步实现</h2><p>分析：</p>
<p>因为 new 的结果是一个新对象，所以在模拟实现的时候，我们也要建立一个新对象，假设这个对象叫 obj，因为 obj 会具有 Otaku 构造函数里的属性，想想经典继承的例子，我们可以使用 Otaku.apply(obj, arguments)来给 obj 添加新的属性。</p>
<p>在 JavaScript 深入系列第一篇中，我们便讲了原型与原型链，我们知道实例的 <strong>proto</strong> 属性会指向构造函数的 prototype，也正是因为建立起这样的关系，实例可以访问原型上的属性。</p>
<p>现在，我们可以尝试着写第一版了：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 第一版代码</span><br><span class="line">function objectFactory() &#123;</span><br><span class="line">	&#x2F;&#x2F; 新建对象</span><br><span class="line">    var obj &#x3D; new Object();</span><br><span class="line">    &#x2F;&#x2F; 移除参数首个</span><br><span class="line">    Constructor &#x3D; [].shift.call(arguments);</span><br><span class="line">    &#x2F;&#x2F; 实例的 __proto__ 属性会指向构造函数的 prototype</span><br><span class="line">    obj.__proto__ &#x3D; Constructor.prototype;</span><br><span class="line">    &#x2F;&#x2F; 调用对象</span><br><span class="line">    Constructor.apply(obj, arguments);</span><br><span class="line">    return obj;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>在这一版中，我们：</p>
<ol>
<li>用new Object() 的方式新建了一个对象 obj</li>
<li>取出第一个参数，就是我们要传入的构造函数。此外因为 shift 会修改原数组，所以 arguments 会被去除第一个参数</li>
<li>将 obj 的原型指向构造函数，这样 obj 就可以访问到构造函数原型中的属性</li>
<li>使用 apply，改变构造函数 this 的指向到新建的对象，这样 obj 就可以访问到构造函数中的属性</li>
<li>返回 obj</li>
</ol>
<p><a target="_blank" rel="noopener" href="https://github.com/mqyqingfeng/Blog/issues/16">https://github.com/mqyqingfeng/Blog/issues/16</a>)</p>
<p>复制以下的代码，到浏览器中，我们可以做一下测试：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">function Otaku (name, age) &#123;</span><br><span class="line">    this.name &#x3D; name;</span><br><span class="line">    this.age &#x3D; age;</span><br><span class="line"></span><br><span class="line">    this.habit &#x3D; &#39;Games&#39;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Otaku.prototype.strength &#x3D; 60;</span><br><span class="line"></span><br><span class="line">Otaku.prototype.sayYourName &#x3D; function () &#123;</span><br><span class="line">    console.log(&#39;I am &#39; + this.name);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function objectFactory() &#123;</span><br><span class="line">    var obj &#x3D; new Object(),</span><br><span class="line">    Constructor &#x3D; [].shift.call(arguments);</span><br><span class="line">    obj.__proto__ &#x3D; Constructor.prototype;</span><br><span class="line">    Constructor.apply(obj, arguments);</span><br><span class="line">    return obj;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">var person &#x3D; objectFactory(Otaku, &#39;Kevin&#39;, &#39;18&#39;)</span><br><span class="line"></span><br><span class="line">console.log(person.name) &#x2F;&#x2F; Kevin</span><br><span class="line">console.log(person.habit) &#x2F;&#x2F; Games</span><br><span class="line">console.log(person.strength) &#x2F;&#x2F; 60</span><br><span class="line"></span><br><span class="line">person.sayYourName(); &#x2F;&#x2F; I am Kevin</span><br></pre></td></tr></table></figure>

<h2 id="返回值效果实现"><a href="#返回值效果实现" class="headerlink" title="返回值效果实现"></a>返回值效果实现</h2><p>接下来我们再来看一种情况，假如构造函数有返回值，举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">function Otaku (name, age) &#123;</span><br><span class="line">    this.strength &#x3D; 60;</span><br><span class="line">    this.age &#x3D; age;</span><br><span class="line"></span><br><span class="line">    return &#123;</span><br><span class="line">        name: name,</span><br><span class="line">        habit: &#39;Games&#39;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var person &#x3D; new Otaku(&#39;Kevin&#39;, &#39;18&#39;);</span><br><span class="line"></span><br><span class="line">console.log(person.name) &#x2F;&#x2F; Kevin</span><br><span class="line">console.log(person.habit) &#x2F;&#x2F; Games</span><br><span class="line">console.log(person.strength) &#x2F;&#x2F; undefined</span><br><span class="line">console.log(person.age) &#x2F;&#x2F; undefined</span><br></pre></td></tr></table></figure>

<p>在这个例子中，构造函数返回了一个对象，在实例 person 中只能访问返回的对象中的属性。</p>
<p>而且还要注意一点，在这里我们是返回了一个对象，假如我们只是返回一个基本类型的值呢？</p>
<p>再举个例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">function Otaku (name, age) &#123;</span><br><span class="line">    this.strength &#x3D; 60;</span><br><span class="line">    this.age &#x3D; age;</span><br><span class="line"></span><br><span class="line">    return &#39;handsome boy&#39;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var person &#x3D; new Otaku(&#39;Kevin&#39;, &#39;18&#39;);</span><br><span class="line"></span><br><span class="line">console.log(person.name) &#x2F;&#x2F; undefined</span><br><span class="line">console.log(person.habit) &#x2F;&#x2F; undefined</span><br><span class="line">console.log(person.strength) &#x2F;&#x2F; 60</span><br><span class="line">console.log(person.age) &#x2F;&#x2F; 18</span><br></pre></td></tr></table></figure>

<p>结果完全颠倒过来，这次尽管有返回值，但是相当于没有返回值进行处理。</p>
<p>所以我们还需要判断返回的值是不是一个对象，如果是一个对象，我们就返回这个对象，如果没有，我们该返回什么就返回什么。</p>
<p>再来看第二版的代码，也是最后一版的代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 第二版的代码</span><br><span class="line">function objectFactory() &#123;</span><br><span class="line">    var obj &#x3D; new Object(),</span><br><span class="line">    Constructor &#x3D; [].shift.call(arguments);</span><br><span class="line">    obj.__proto__ &#x3D; Constructor.prototype;</span><br><span class="line">    var ret &#x3D; Constructor.apply(obj, arguments);</span><br><span class="line">    return typeof ret &#x3D;&#x3D;&#x3D; &#39;object&#39; ? ret : obj;</span><br><span class="line"></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="15-Event-Loop（事件循环）机制"><a href="#15-Event-Loop（事件循环）机制" class="headerlink" title="15.Event Loop（事件循环）机制"></a>15.Event Loop（事件循环）机制</h1><h2 id="前言-1"><a href="#前言-1" class="headerlink" title="前言"></a>前言</h2><p>我们都知道，javascript从诞生之日起就是一门单线程的非阻塞的脚本语言。这是由其最初的用途来决定的：与浏览器交互。</p>
<p>单线程意味着，javascript代码在执行的任何时候，都只有一个主线程来处理所有的任务。</p>
<p>而非阻塞则是当代码需要进行一项异步任务（无法立刻返回结果，需要花一定时间才能返回的任务，如I/O事件）的时候，主线程会挂起（pending）这个任务，然后在异步任务返回结果的时候再根据一定规则去执行相应的回调。</p>
<p>单线程是必要的，也是javascript这门语言的基石，原因之一在其最初也是最主要的执行环境——浏览器中，我们需要进行各种各样的dom操作。试想一下 如果javascript是多线程的，那么当两个线程同时对dom进行一项操作，例如一个向其添加事件，而另一个删除了这个dom，此时该如何处理呢？因此，为了保证不会 发生类似于这个例子中的情景，javascript选择只用一个主线程来执行代码，这样就保证了程序执行的一致性。</p>
<p>当然，现如今人们也意识到，单线程在保证了执行顺序的同时也限制了javascript的效率，因此开发出了web worker技术。这项技术号称让javascript成为一门多线程语言。</p>
<p>然而，使用web worker技术开的多线程有着诸多限制，例如：所有新线程都受主线程的完全控制，不能独立执行。这意味着这些“线程” 实际上应属于主线程的子线程。另外，这些子线程并没有执行I/O操作的权限，只能为主线程分担一些诸如计算等任务。所以严格来讲这些线程并没有完整的功能，也因此这项技术并非改变了javascript语言的单线程本质。</p>
<p>可以预见，未来的javascript也会一直是一门单线程的语言。</p>
<p>话说回来，前面提到javascript的另一个特点是“非阻塞”，那么javascript引擎到底是如何实现的这一点呢？答案就是今天这篇文章的主角——event loop（事件循环）。</p>
<p><em>注：虽然nodejs中的也存在与传统浏览器环境下的相似的事件循环。然而两者间却有着诸多不同，故把两者分开，单独解释。</em></p>
<h2 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h2><h2 id="浏览器环境下js引擎的事件循环机制"><a href="#浏览器环境下js引擎的事件循环机制" class="headerlink" title="浏览器环境下js引擎的事件循环机制"></a><strong>浏览器环境下js引擎的事件循环机制</strong></h2><h2 id="1-执行栈与事件队列"><a href="#1-执行栈与事件队列" class="headerlink" title="1.执行栈与事件队列"></a><strong>1.执行栈与事件队列</strong></h2><p>当javascript代码执行的时候会将不同的变量存于内存中的不同位置：堆（heap）和栈（stack）中来加以区分。其中，堆里存放着一些对象。而栈中则存放着一些基础类型变量以及对象的指针。 但是我们这里说的执行栈和上面这个栈的意义却有些不同。</p>
<p>我们知道，当我们调用一个方法的时候，js会生成一个与这个方法对应的执行环境（context），又叫执行上下文。这个执行环境中存在着这个方法的私有作用域，上层作用域的指向，方法的参数，这个作用域中定义的变量以及这个作用域的this对象。 而当一系列方法被依次调用的时候，因为js是单线程的，同一时间只能执行一个方法，于是这些方法被排队在一个单独的地方。这个地方被称为执行栈。</p>
<p>当一个脚本第一次执行的时候，js引擎会解析这段代码，并将其中的同步代码按照执行顺序加入执行栈中，然后从头开始执行。如果当前执行的是一个方法，那么js会向执行栈中添加这个方法的执行环境，然后进入这个执行环境继续执行其中的代码。当这个执行环境中的代码 执行完毕并返回结果后，js会退出这个执行环境并把这个执行环境销毁，回到上一个方法的执行环境。。这个过程反复进行，直到执行栈中的代码全部执行完毕。</p>
<p>下面这个图片非常直观的展示了这个过程，其中的global就是初次运行脚本时向执行栈中加入的代码：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144754.jpeg" alt="img"></p>
<p>从图片可知，一个方法执行会向执行栈中加入这个方法的执行环境，在这个执行环境中还可以调用其他方法，甚至是自己，其结果不过是在执行栈中再添加一个执行环境。这个过程可以是无限进行下去的，除非发生了栈溢出，即超过了所能使用内存的最大值。</p>
<p>以上的过程说的都是同步代码的执行。那么当一个异步代码（如发送ajax请求数据）执行后会如何呢？前文提过，js的另一大特点是非阻塞，实现这一点的关键在于下面要说的这项机制——事件队列（Task Queue）。</p>
<p>js引擎遇到一个异步事件后并不会一直等待其返回结果，而是会将这个事件挂起，继续执行执行栈中的其他任务。当一个异步事件返回结果后，js会将这个事件加入与当前执行栈不同的另一个队列，我们称之为事件队列。被放入事件队列不会立刻执行其回调，而是等待当前执行栈中的所有任务都执行完毕， 主线程处于闲置状态时，主线程会去查找事件队列是否有任务。如果有，那么主线程会从中取出排在第一位的事件，并把这个事件对应的回调放入执行栈中，然后执行其中的同步代码…，如此反复，这样就形成了一个无限的循环。这就是这个过程被称为“事件循环（Event Loop）”的原因。</p>
<p>这里还有一张图来展示这个过程：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144357.png" alt="img"></p>
<p>图中的stack表示我们所说的执行栈，web apis则是代表一些异步事件，而callback queue即事件队列。</p>
<h2 id="2-macro-task与micro-task"><a href="#2-macro-task与micro-task" class="headerlink" title="2.macro task与micro task"></a><strong>2.macro task与micro task</strong></h2><p>以上的事件循环过程是一个宏观的表述，实际上因为异步任务之间并不相同，因此他们的执行优先级也有区别。不同的异步任务被分为两类：微任务（micro task）和宏任务（macro task）。</p>
<p>以下事件属于宏任务：</p>
<ul>
<li><code>setInterval()</code></li>
<li><code>setTimeout()</code></li>
</ul>
<p>以下事件属于微任务</p>
<ul>
<li><code>new Promise()</code></li>
<li><code>new MutaionObserver()</code></li>
</ul>
<p>前面我们介绍过，在一个事件循环中，异步事件返回结果后会被放到一个任务队列中。然而，根据这个异步事件的类型，这个事件实际上会被对应的宏任务队列或者微任务队列中去。并且在当前执行栈为空的时候，主线程会 查看微任务队列是否有事件存在。如果不存在，那么再去宏任务队列中取出一个事件并把对应的回到加入当前执行栈；如果存在，则会依次执行队列中事件对应的回调，直到微任务队列为空，然后去宏任务队列中取出最前面的一个事件，把对应的回调加入当前执行栈…如此反复，进入循环。</p>
<p>我们只需记住<strong>当当前执行栈执行完毕时会立刻先处理所有微任务队列中的事件，然后再去宏任务队列中取出一个事件。同一次事件循环中，微任务永远在宏任务之前执行</strong>。</p>
<p>这样就能解释下面这段代码的结果：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">setTimeout(function () &#123;</span><br><span class="line">    console.log(1);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">new Promise(function(resolve,reject)&#123;</span><br><span class="line">    console.log(2)</span><br><span class="line">    resolve(3)</span><br><span class="line">&#125;).then(function(val)&#123;</span><br><span class="line">    console.log(val);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>结果为：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">2</span><br><span class="line">3</span><br><span class="line">1 </span><br></pre></td></tr></table></figure>

<h2 id="node环境下的事件循环机制"><a href="#node环境下的事件循环机制" class="headerlink" title="node环境下的事件循环机制"></a><strong>node环境下的事件循环机制</strong></h2><h2 id="1-与浏览器环境有何不同"><a href="#1-与浏览器环境有何不同" class="headerlink" title="1.与浏览器环境有何不同?"></a><strong>1.与浏览器环境有何不同?</strong></h2><p>在node中，事件循环表现出的状态与浏览器中大致相同。不同的是node中有一套自己的模型。node中事件循环的实现是依靠的libuv引擎。我们知道node选择chrome v8引擎作为js解释器，v8引擎将js代码分析后去调用对应的node api，而这些api最后则由libuv引擎驱动，执行对应的任务，并把不同的事件放在不同的队列中等待主线程执行。 因此实际上node中的事件循环存在于libuv引擎中。</p>
<h2 id="2-事件循环模型"><a href="#2-事件循环模型" class="headerlink" title="2.事件循环模型"></a><strong>2.事件循环模型</strong></h2><p>下面是一个libuv引擎中的事件循环的模型:</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">   ┌───────────────────────┐</span><br><span class="line">┌─&gt;│        timers         │</span><br><span class="line">│  └──────────┬────────────┘</span><br><span class="line">│  ┌──────────┴────────────┐</span><br><span class="line">│  │     I/O callbacks     │</span><br><span class="line">│  └──────────┬────────────┘</span><br><span class="line">│  ┌──────────┴────────────┐</span><br><span class="line">│  │     idle, prepare     │</span><br><span class="line">│  └──────────┬────────────┘      ┌───────────────┐</span><br><span class="line">│  ┌──────────┴────────────┐      │   incoming:   │</span><br><span class="line">│  │         poll          │&lt;──connections───     │</span><br><span class="line">│  └──────────┬────────────┘      │   data, etc.  │</span><br><span class="line">│  ┌──────────┴────────────┐      └───────────────┘</span><br><span class="line">│  │        check          │</span><br><span class="line">│  └──────────┬────────────┘</span><br><span class="line">│  ┌──────────┴────────────┐</span><br><span class="line">└──┤    close callbacks    │</span><br><span class="line">   └───────────────────────┘</span><br></pre></td></tr></table></figure>

<p><em>注：模型中的每一个方块代表事件循环的一个阶段</em></p>
<p>这个模型是node官网上的一篇文章中给出的，我下面的解释也都来源于这篇文章。我会在文末把文章地址贴出来，有兴趣的朋友可以亲自与看看原文。</p>
<h2 id="3-事件循环各阶段详解"><a href="#3-事件循环各阶段详解" class="headerlink" title="3.事件循环各阶段详解"></a><strong>3.事件循环各阶段详解</strong></h2><p>从上面这个模型中，我们可以大致分析出node中的事件循环的顺序：</p>
<p>外部输入数据–&gt;轮询阶段(poll)–&gt;检查阶段(check)–&gt;关闭事件回调阶段(close callback)–&gt;定时器检测阶段(timer)–&gt;I/O事件回调阶段(I/O callbacks)–&gt;闲置阶段(idle, prepare)–&gt;轮询阶段…</p>
<p>以上各阶段的名称是根据我个人理解的翻译，为了避免错误和歧义，下面解释的时候会用英文来表示这些阶段。</p>
<p>这些阶段大致的功能如下：</p>
<ul>
<li>timers: 这个阶段执行定时器队列中的回调如 <code>setTimeout()</code> 和 <code>setInterval()</code>。</li>
<li>I/O callbacks: 这个阶段执行几乎所有的回调。但是不包括close事件，定时器和<code>setImmediate()</code>的回调。</li>
<li>idle, prepare: 这个阶段仅在内部使用，可以不必理会。</li>
<li>poll: 等待新的I/O事件，node在一些特殊情况下会阻塞在这里。</li>
<li>check: <code>setImmediate()</code>的回调会在这个阶段执行。</li>
<li>close callbacks: 例如<code>socket.on(&#39;close&#39;, ...)</code>这种close事件的回调。</li>
</ul>
<p>下面我们来按照代码第一次进入libuv引擎后的顺序来详细解说这些阶段：</p>
<h2 id="poll阶段"><a href="#poll阶段" class="headerlink" title="poll阶段"></a><strong>poll阶段</strong></h2><p>当个v8引擎将js代码解析后传入libuv引擎后，循环首先进入poll阶段。poll阶段的执行逻辑如下： 先查看poll queue中是否有事件，有任务就按先进先出的顺序依次执行回调。 当queue为空时，会检查是否有setImmediate()的callback，如果有就进入check阶段执行这些callback。但同时也会检查是否有到期的timer，如果有，就把这些到期的timer的callback按照调用顺序放到timer queue中，之后循环会进入timer阶段执行queue中的 callback。 这两者的顺序是不固定的，收到代码运行的环境的影响。如果两者的queue都是空的，那么loop会在poll阶段停留，直到有一个i/o事件返回，循环会进入i/o callback阶段并立即执行这个事件的callback。</p>
<p>值得注意的是，poll阶段在执行poll queue中的回调时实际上不会无限的执行下去。有两种情况poll阶段会终止执行poll queue中的下一个回调：1.所有回调执行完毕。2.执行数超过了node的限制。</p>
<h2 id="check阶段"><a href="#check阶段" class="headerlink" title="check阶段"></a><strong>check阶段</strong></h2><p>check阶段专门用来执行<code>setImmediate()</code>方法的回调，当poll阶段进入空闲状态，并且setImmediate queue中有callback时，事件循环进入这个阶段。</p>
<h2 id="close阶段"><a href="#close阶段" class="headerlink" title="close阶段"></a><strong>close阶段</strong></h2><p>当一个socket连接或者一个handle被突然关闭时（例如调用了<code>socket.destroy()</code>方法），close事件会被发送到这个阶段执行回调。否则事件会用<code>process.nextTick（）</code>方法发送出去。</p>
<h2 id="timer阶段"><a href="#timer阶段" class="headerlink" title="timer阶段"></a><strong>timer阶段</strong></h2><p>这个阶段以先进先出的方式执行所有到期的timer加入timer队列里的callback，一个timer callback指得是一个通过setTimeout或者setInterval函数设置的回调函数。</p>
<h2 id="I-O-callback阶段"><a href="#I-O-callback阶段" class="headerlink" title="I/O callback阶段"></a><strong>I/O callback阶段</strong></h2><p>如上文所言，这个阶段主要执行大部分I/O事件的回调，包括一些为操作系统执行的回调。例如一个TCP连接生错误时，系统需要执行回调来获得这个错误的报告。</p>
<h2 id="4-process-nextTick-setTimeout与setImmediate的区别与使用场景"><a href="#4-process-nextTick-setTimeout与setImmediate的区别与使用场景" class="headerlink" title="4.process.nextTick,setTimeout与setImmediate的区别与使用场景"></a><strong>4.process.nextTick,setTimeout与setImmediate的区别与使用场景</strong></h2><p>在node中有三个常用的用来推迟任务执行的方法：process.nextTick,setTimeout（setInterval与之相同）与setImmediate</p>
<p>这三者间存在着一些非常不同的区别：</p>
<h2 id="process-nextTick"><a href="#process-nextTick" class="headerlink" title="process.nextTick()"></a><strong>process.nextTick()</strong></h2><p>尽管没有提及，但是实际上node中存在着一个特殊的队列，即nextTick queue。这个队列中的回调执行虽然没有被表示为一个阶段，当时这些事件却会在每一个阶段执行完毕准备进入下一个阶段时优先执行。当事件循环准备进入下一个阶段之前，会先检查nextTick queue中是否有任务，如果有，那么会先清空这个队列。与执行poll queue中的任务不同的是，这个操作在队列清空前是不会停止的。这也就意味着，错误的使用<code>process.nextTick()</code>方法会导致node进入一个死循环。。直到内存泄漏。</p>
<p>那么合适使用这个方法比较合适呢？下面有一个例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> server = net.createServer(<span class="function">() =&gt;</span> &#123;&#125;).listen(<span class="number">8080</span>);</span><br><span class="line"></span><br><span class="line">server.on(<span class="string">&#x27;listening&#x27;</span>, <span class="function">() =&gt;</span> &#123;&#125;);</span><br></pre></td></tr></table></figure>

<p>这个例子中当，当listen方法被调用时，除非端口被占用，否则会立刻绑定在对应的端口上。这意味着此时这个端口可以立刻触发listening事件并执行其回调。然而，这时候<code>on(&#39;listening)</code>还没有将callback设置好，自然没有callback可以执行。为了避免出现这种情况，node会在listen事件中使用<code>process.nextTick()</code>方法，确保事件在回调函数绑定后被触发。</p>
<h2 id="setTimeout-和setImmediate"><a href="#setTimeout-和setImmediate" class="headerlink" title="setTimeout()和setImmediate()"></a><strong>setTimeout()和setImmediate()</strong></h2><p>在三个方法中，这两个方法最容易被弄混。实际上，某些情况下这两个方法的表现也非常相似。然而实际上，这两个方法的意义却大为不同。</p>
<p><code>setTimeout()</code>方法是定义一个回调，并且希望这个回调在我们所指定的时间间隔后第一时间去执行。注意这个“第一时间执行”，这意味着，受到操作系统和当前执行任务的诸多影响，该回调并不会在我们预期的时间间隔后精准的执行。执行的时间存在一定的延迟和误差，这是不可避免的。node会在可以执行timer回调的第一时间去执行你所设定的任务。</p>
<p><code>setImmediate()</code>方法从意义上将是立刻执行的意思，但是实际上它却是在一个固定的阶段才会执行回调，即poll阶段之后。有趣的是，这个名字的意义和之前提到过的<code>process.nextTick()</code>方法才是最匹配的。node的开发者们也清楚这两个方法的命名上存在一定的混淆，他们表示不会把这两个方法的名字调换过来—因为有大量的node程序使用着这两个方法，调换命名所带来的好处与它的影响相比不值一提。</p>
<p><code>setTimeout()</code>和不设置时间间隔的<code>setImmediate()</code>表现上及其相似。猜猜下面这段代码的结果是什么？</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">setTimeout(() =&gt; &#123;</span><br><span class="line">    console.log(&#x27;timeout&#x27;);</span><br><span class="line">&#125;, 0);</span><br><span class="line"></span><br><span class="line">setImmediate(() =&gt; &#123;</span><br><span class="line">    console.log(&#x27;immediate&#x27;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>实际上，答案是不一定。没错，就连node的开发者都无法准确的判断这两者的顺序谁前谁后。这取决于这段代码的运行环境。运行环境中的各种复杂的情况会导致在同步队列里两个方法的顺序随机决定。但是，在一种情况下可以准确判断两个方法回调的执行顺序，那就是在一个I/O事件的回调中。下面这段代码的顺序永远是固定的：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">const fs = require(&#x27;fs&#x27;);</span><br><span class="line"></span><br><span class="line">fs.readFile(__filename, () =&gt; &#123;</span><br><span class="line">    setTimeout(() =&gt; &#123;</span><br><span class="line">        console.log(&#x27;timeout&#x27;);</span><br><span class="line">    &#125;, 0);</span><br><span class="line">    setImmediate(() =&gt; &#123;</span><br><span class="line">        console.log(&#x27;immediate&#x27;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>答案永远是：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">immediate</span><br><span class="line">timeout</span><br></pre></td></tr></table></figure>

<p>因为在I/O事件的回调中，setImmediate方法的回调永远在timer的回调前执行。</p>
<p><strong>尾声</strong></p>
<p>javascrit的事件循环是这门语言中非常重要且基础的概念。清楚的了解了事件循环的执行顺序和每一个阶段的特点，可以使我们对一段异步代码的执行顺序有一个清晰的认识，从而减少代码运行的不确定性。合理的使用各种延迟事件的方法，有助于代码更好的按照其优先级去执行。这篇文章期望用最易理解的方式和语言准确描述事件循环这个复杂过程，但由于作者自己水平有限，文章中难免出现疏漏。如果您发现了文章中的一些问题，欢迎在留言中提出，我会尽量回复这些评论，把错误更正。</p>
<h1 id="16-Promise-原理"><a href="#16-Promise-原理" class="headerlink" title="16.Promise 原理"></a>16.Promise 原理</h1><p>Promise 必须为以下三种状态之一：等待态（Pending）、执行态（Fulfilled）和拒绝态（Rejected）。一旦Promise 被 resolve 或 reject，不能再迁移至其他任何状态（即状态 immutable）。</p>
<p>基本过程：</p>
<ol>
<li>初始化 Promise 状态（pending）</li>
<li>立即执行 Promise 中传入的 fn 函数，将Promise 内部 resolve、reject 函数作为参数传递给 fn ，按事件机制时机处理</li>
<li>执行 then(..) 注册回调处理数组（then 方法可被同一个 promise 调用多次）</li>
<li>Promise里的关键是要保证，then方法传入的参数 onFulfilled 和 onRejected，必须在then方法被调用的那一轮事件循环之后的新执行栈中执行。</li>
</ol>
<p><strong>真正的链式Promise是指在当前promise达到fulfilled状态后，即开始进行下一个promise.</strong></p>
<h3 id="链式调用"><a href="#链式调用" class="headerlink" title="链式调用"></a>链式调用</h3><p>先从 Promise 执行结果看一下，有如下一段代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        resolve(&#123; <span class="attr">test</span>: <span class="number">1</span> &#125;)</span><br><span class="line">        resolve(&#123; <span class="attr">test</span>: <span class="number">2</span> &#125;)</span><br><span class="line">        reject(&#123; <span class="attr">test</span>: <span class="number">2</span> &#125;)</span><br><span class="line">    &#125;, <span class="number">1000</span>)</span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;result1&#x27;</span>, data)</span><br><span class="line">&#125;,<span class="function">(<span class="params">data1</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;result2&#x27;</span>,data1)</span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;result3&#x27;</span>, data)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//result1 &#123; test: 1 &#125;</span></span><br><span class="line"><span class="comment">//result3 undefined</span></span><br></pre></td></tr></table></figure>

<p>显然这里输出了不同的 data。由此可以看出几点：</p>
<ol>
<li>可进行链式调用，且每次 then 返回了新的 Promise(2次打印结果不一致，如果是同一个实例，打印结果应该一致。</li>
<li>只输出第一次 resolve 的内容，reject 的内容没有输出，即 Promise 是有状态且状态只可以由pending -&gt; fulfilled或 pending-&gt; rejected,是不可逆的。</li>
<li>then 中返回了新的 Promise,但是then中注册的回调仍然是属于上一个 Promise 的。</li>
</ol>
<p>基于以上几点，我们先写个基于 <a target="_blank" rel="noopener" href="https://promisesaplus.com/">PromiseA+</a> 规范的只含 resolve 方法的 Promise 模型:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Promise</span>(<span class="params">fn</span>)</span>&#123; </span><br><span class="line">    <span class="keyword">let</span> state = <span class="string">&#x27;pending&#x27;</span>;</span><br><span class="line">    <span class="keyword">let</span> value = <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">const</span> callbacks = [];</span><br><span class="line"></span><br><span class="line">    <span class="built_in">this</span>.then = <span class="function"><span class="keyword">function</span> (<span class="params">onFulfilled</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>)=&gt;</span>&#123;</span><br><span class="line">            handle(&#123; <span class="comment">//桥梁，将新 Promise 的 resolve 方法，放到前一个 promise 的回调对象中</span></span><br><span class="line">                onFulfilled, </span><br><span class="line">                resolve</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">handle</span>(<span class="params">callback</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(state === <span class="string">&#x27;pending&#x27;</span>)&#123;</span><br><span class="line">            callbacks.push(callback)</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(state === <span class="string">&#x27;fulfilled&#x27;</span>)&#123;</span><br><span class="line">            <span class="keyword">if</span>(!callback.onFulfilled)&#123;</span><br><span class="line">                callback.resolve(value)</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">const</span> ret = callback.onFulfilled(value) <span class="comment">//处理回调</span></span><br><span class="line">            callback.resolve(ret) <span class="comment">//处理下一个 promise 的resolve</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">resolve</span>(<span class="params">newValue</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">const</span> fn = <span class="function">()=&gt;</span>&#123;</span><br><span class="line">            <span class="keyword">if</span>(state !== <span class="string">&#x27;pending&#x27;</span>)<span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">            state = <span class="string">&#x27;fulfilled&#x27;</span>;</span><br><span class="line">            value = newValue</span><br><span class="line">            handelCb()</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">setTimeout</span>(fn,<span class="number">0</span>) <span class="comment">//基于 PromiseA+ 规范</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">handelCb</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">while</span>(callbacks.length) &#123;</span><br><span class="line">            <span class="keyword">const</span> fulfiledFn = callbacks.shift();</span><br><span class="line">            handle(fulfiledFn);</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    fn(resolve)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>这个模型简单易懂，这里最关键的点就是在 then 中新创建的 Promise，它的状态变为 fulfilled 的节点是在上一个 Promise的回调执行完毕的时候。也就是说当一个 Promise 的状态被 fulfilled 之后，会执行其回调函数，而回调函数返回的结果会被当作 value，返回给下一个 Promise(也就是then 中产生的 Promise)，同时下一个 Promise的状态也会被改变(执行 resolve 或 reject)，然后再去执行其回调,以此类推下去…链式调用的效应就出来了。</strong></p>
<p>但是如果仅仅是例子中的情况，我们可以这样写：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">new Promise((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">    setTimeout(() &#x3D;&gt; &#123;</span><br><span class="line">        resolve(&#123; test: 1 &#125;)</span><br><span class="line">    &#125;, 1000)</span><br><span class="line">&#125;).then((data) &#x3D;&gt; &#123;</span><br><span class="line">    console.log(&#39;result1&#39;, data)</span><br><span class="line">    &#x2F;&#x2F;dosomething</span><br><span class="line">    console.log(&#39;result3&#39;)</span><br><span class="line">&#125;)</span><br><span class="line">&#x2F;&#x2F;result1 &#123; test: 1 &#125;</span><br><span class="line">&#x2F;&#x2F;result3</span><br></pre></td></tr></table></figure>

<p>实际上，我们常用的链式调用，是用在异步回调中，以解决”回调地狱”的问题。如下例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">new Promise((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">  setTimeout(() &#x3D;&gt; &#123;</span><br><span class="line">    resolve(&#123; test: 1 &#125;)</span><br><span class="line">  &#125;, 1000)</span><br><span class="line">&#125;).then((data) &#x3D;&gt; &#123;</span><br><span class="line">  console.log(&#39;result1&#39;, data)</span><br><span class="line">  &#x2F;&#x2F;dosomething</span><br><span class="line">  return test()</span><br><span class="line">&#125;).then((data) &#x3D;&gt; &#123;</span><br><span class="line">  console.log(&#39;result2&#39;, data)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">function test(id) &#123;</span><br><span class="line">  return new Promise(((resolve) &#x3D;&gt; &#123;</span><br><span class="line">    setTimeout(() &#x3D;&gt; &#123;</span><br><span class="line">      resolve(&#123; test: 2 &#125;)</span><br><span class="line">    &#125;, 5000)</span><br><span class="line">  &#125;))</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;基于第一个 Promise 模型，执行后的输出</span><br><span class="line">&#x2F;&#x2F;result1 &#123; test: 1 &#125;</span><br><span class="line">&#x2F;&#x2F;result2 Promise &#123;then: ƒ&#125;</span><br></pre></td></tr></table></figure>

<p>用上面的 Promise 模型，得到的结果显然不是我们想要的。认真看上面的模型，执行 callback.resolve 时，传入的参数是 callback.onFulfilled 执行完成的返回，显然这个测试例子返回的就是一个 Promise，而我们的 Promise 模型中的 resolve 方法并没有特殊处理。那么我们将 resolve 改一下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">function Promise(fn)&#123; </span><br><span class="line">    ...</span><br><span class="line">    function resolve(newValue)&#123;</span><br><span class="line">        const fn &#x3D; ()&#x3D;&gt;&#123;</span><br><span class="line">            if(state !&#x3D;&#x3D; &#39;pending&#39;)return</span><br><span class="line"></span><br><span class="line">            if(newValue &amp;&amp; (typeof newValue &#x3D;&#x3D;&#x3D; &#39;object&#39; || typeof newValue &#x3D;&#x3D;&#x3D; &#39;function&#39;))&#123;</span><br><span class="line">                const &#123;then&#125; &#x3D; newValue</span><br><span class="line">                if(typeof then &#x3D;&#x3D;&#x3D; &#39;function&#39;)&#123;</span><br><span class="line">                    &#x2F;&#x2F; newValue 为新产生的 Promise,此时resolve为上个 promise 的resolve</span><br><span class="line">                    &#x2F;&#x2F;相当于调用了新产生 Promise 的then方法，注入了上个 promise 的resolve 为其回调</span><br><span class="line">                    then.call(newValue,resolve)</span><br><span class="line">                    return</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            state &#x3D; &#39;fulfilled&#39;;</span><br><span class="line">            value &#x3D; newValue</span><br><span class="line">            handelCb()</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        setTimeout(fn,0)</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>用这个模型，再测试我们的例子，就得到了正确的结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">new Promise((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">    setTimeout(() &#x3D;&gt; &#123;</span><br><span class="line">        resolve(&#123; test: 1 &#125;)</span><br><span class="line">    &#125;, 1000)</span><br><span class="line">&#125;).then((data) &#x3D;&gt; &#123;</span><br><span class="line">    console.log(&#39;result1&#39;, data)</span><br><span class="line">    &#x2F;&#x2F;dosomething</span><br><span class="line">    return test()</span><br><span class="line">&#125;).then((data) &#x3D;&gt; &#123;</span><br><span class="line">    console.log(&#39;result2&#39;, data)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">function test(id) &#123;</span><br><span class="line">    return new Promise(((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">        setTimeout(() &#x3D;&gt; &#123;</span><br><span class="line">        resolve(&#123; test: 2 &#125;)</span><br><span class="line">        &#125;, 5000)</span><br><span class="line">    &#125;))</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; result1 &#123; test: 1 &#125;</span><br><span class="line">&#x2F;&#x2F; result2 &#123; test: 2 &#125;</span><br></pre></td></tr></table></figure>

<p>显然，新增的逻辑就是针对 resolve 入参为 Promise 的时候的处理。我们观察一下 test 里面创建的 Promise，它是没有调用 then方法的。从上面的分析我们已经知道 Promise 的回调函数就是通过调用其 then 方法注册的，因此 test 里面创建的 Promise 其回调函数为空。</p>
<p>显然如果没有回调函数，执行 resolve 的时候，是没办法链式下去的。因此，我们需要主动为其注入回调函数。</p>
<p>我们只要把第一个 then 中产生的 Promise 的 resolve 函数的执行，延迟到 test 里面的 Promise 的状态为 onFulfilled 的时候再执行，那么链式就可以继续了。所以，当 resolve 入参为 Promise 的时候，调用其 then 方法为其注入回调函数，而注入的是前一个 Promise 的 resolve 方法，所以要用 call 来绑定 this 的指向。</p>
<p>基于新的 Promise 模型，上面的执行过程产生的 Promise 实例及其回调函数，可以用看下表：</p>
<table>
<thead>
<tr>
<th>Promise</th>
<th>callback</th>
</tr>
</thead>
<tbody><tr>
<td>P1</td>
<td>[{onFulfilled:c1(第一个then中的fn),resolve:p2resolve}]</td>
</tr>
<tr>
<td>P2 (P1 调用 then 时产生)</td>
<td>[{onFulfilled:c2(第二个then中的fn),resolve:p3resolve}]</td>
</tr>
<tr>
<td>P3 (P2 调用 then 时产生)</td>
<td>[]</td>
</tr>
<tr>
<td>P4 (执行c1中产生[调用 test ])</td>
<td>[{onFulfilled:p2resolve,resolve:p5resolve}]</td>
</tr>
<tr>
<td>P5 (调用p2resolve 时，进入 then.call 逻辑中产生)</td>
<td>[]</td>
</tr>
</tbody></table>
<p>有了这个表格，我们就可以清晰知道各个实例中 callback 执行的顺序是：</p>
<p>c1 -&gt; p2resolve -&gt; c2 -&gt; p3resolve -&gt; [] -&gt; p5resolve -&gt; []</p>
<p>以上就是链式调用的原理了。</p>
<h3 id="reject"><a href="#reject" class="headerlink" title="reject"></a>reject</h3><p>下面我们再来补全 reject 的逻辑。只需要在注册回调、状态改变时加上 reject 的逻辑即可。</p>
<p>完整代码如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line">function Promise(fn)&#123; </span><br><span class="line">    let state &#x3D; &#39;pending&#39;;</span><br><span class="line">    let value &#x3D; null;</span><br><span class="line">    const callbacks &#x3D; [];</span><br><span class="line"></span><br><span class="line">    this.then &#x3D; function (onFulfilled,onRejected)&#123;</span><br><span class="line">        return new Promise((resolve, reject)&#x3D;&gt;&#123;</span><br><span class="line">            handle(&#123;</span><br><span class="line">                onFulfilled, </span><br><span class="line">                onRejected,</span><br><span class="line">                resolve, </span><br><span class="line">                reject</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function handle(callback)&#123;</span><br><span class="line">        if(state &#x3D;&#x3D;&#x3D; &#39;pending&#39;)&#123;</span><br><span class="line">            callbacks.push(callback)</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        const cb &#x3D; state &#x3D;&#x3D;&#x3D; &#39;fulfilled&#39; ? callback.onFulfilled : callback.onRejected;</span><br><span class="line">        const next &#x3D; state &#x3D;&#x3D;&#x3D; &#39;fulfilled&#39; ? callback.resolve : callback.reject;</span><br><span class="line"></span><br><span class="line">        if(!cb)&#123;</span><br><span class="line">            next(value)</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        const ret &#x3D; cb(value)</span><br><span class="line">        next(ret)</span><br><span class="line">    &#125;</span><br><span class="line">    function resolve(newValue)&#123;</span><br><span class="line">        const fn &#x3D; () &#x3D;&gt; &#123;</span><br><span class="line">            if(state !&#x3D;&#x3D; &#39;pending&#39;)return</span><br><span class="line"></span><br><span class="line">            if(newValue &amp;&amp; (typeof newValue &#x3D;&#x3D;&#x3D; &#39;object&#39; || typeof newValue &#x3D;&#x3D;&#x3D; &#39;function&#39;))&#123;</span><br><span class="line">                const &#123;then&#125; &#x3D; newValue</span><br><span class="line">                if(typeof then &#x3D;&#x3D;&#x3D; &#39;function&#39;)&#123;</span><br><span class="line">                    &#x2F;&#x2F; newValue 为新产生的 Promise,此时resolve为上个 promise 的resolve</span><br><span class="line">                    &#x2F;&#x2F;相当于调用了新产生 Promise 的then方法，注入了上个 promise 的resolve 为其回调</span><br><span class="line">                    then.call(newValue,resolve, reject)</span><br><span class="line">                    return</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            state &#x3D; &#39;fulfilled&#39;;</span><br><span class="line">            value &#x3D; newValue</span><br><span class="line">            handelCb()</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        setTimeout(fn,0)</span><br><span class="line">    &#125;</span><br><span class="line">    function reject(error)&#123;</span><br><span class="line"></span><br><span class="line">        const fn &#x3D; ()&#x3D;&gt;&#123;</span><br><span class="line">            if(state !&#x3D;&#x3D; &#39;pending&#39;)return</span><br><span class="line"></span><br><span class="line">            if(error &amp;&amp; (typeof error &#x3D;&#x3D;&#x3D; &#39;object&#39; || typeof error &#x3D;&#x3D;&#x3D; &#39;function&#39;))&#123;</span><br><span class="line">                const &#123;then&#125; &#x3D; error</span><br><span class="line">                if(typeof then &#x3D;&#x3D;&#x3D; &#39;function&#39;)&#123;</span><br><span class="line">                    then.call(error,resolve, reject)</span><br><span class="line">                    return</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            state &#x3D; &#39;rejected&#39;;</span><br><span class="line">            value &#x3D; error</span><br><span class="line">            handelCb()</span><br><span class="line">        &#125;</span><br><span class="line">        setTimeout(fn,0)</span><br><span class="line">    &#125;</span><br><span class="line">    function handelCb()&#123;</span><br><span class="line">        while(callbacks.length) &#123;</span><br><span class="line">            const fn &#x3D; callbacks.shift();</span><br><span class="line">            handle(fn);</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">    fn(resolve, reject)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h3><p>异常通常是指在执行成功/失败回调时代码出错产生的错误，对于这类异常，我们使用 try-catch 来捕获错误，并将 Promise 设为 rejected 状态即可。</p>
<p>handle代码改造如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">function handle(callback)&#123;</span><br><span class="line">    if(state &#x3D;&#x3D;&#x3D; &#39;pending&#39;)&#123;</span><br><span class="line">        callbacks.push(callback)</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    const cb &#x3D; state &#x3D;&#x3D;&#x3D; &#39;fulfilled&#39; ? callback.onFulfilled : callback.onRejected;</span><br><span class="line">    const next &#x3D; state &#x3D;&#x3D;&#x3D; &#39;fulfilled&#39;? callback.resolve : callback.reject;</span><br><span class="line"></span><br><span class="line">    if(!cb)&#123;</span><br><span class="line">        next(value)</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line">    try &#123;</span><br><span class="line">        const ret &#x3D; cb(value)</span><br><span class="line">        next(ret)</span><br><span class="line">    &#125; catch (e) &#123;</span><br><span class="line">        callback.reject(e);</span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们实际使用时，常习惯注册 catch 方法来处理错误，例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">new Promise((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">    setTimeout(() &#x3D;&gt; &#123;</span><br><span class="line">        resolve(&#123; test: 1 &#125;)</span><br><span class="line">    &#125;, 1000)</span><br><span class="line">&#125;).then((data) &#x3D;&gt; &#123;</span><br><span class="line">    console.log(&#39;result1&#39;, data)</span><br><span class="line">    &#x2F;&#x2F;dosomething</span><br><span class="line">    return test()</span><br><span class="line">&#125;).catch((ex) &#x3D;&gt; &#123;</span><br><span class="line">    console.log(&#39;error&#39;, ex)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>实际上，错误也好，异常也罢，最终都是通过reject实现的。也就是说可以通过 then 中的错误回调来处理。所以我们可以增加这样的一个 catch 方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">function Promise(fn)&#123; </span><br><span class="line">    ...</span><br><span class="line">    this.then &#x3D; function (onFulfilled,onRejected)&#123;</span><br><span class="line">        return new Promise((resolve, reject)&#x3D;&gt;&#123;</span><br><span class="line">            handle(&#123;</span><br><span class="line">                onFulfilled, </span><br><span class="line">                onRejected,</span><br><span class="line">                resolve, </span><br><span class="line">                reject</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    this.catch &#x3D; function (onError)&#123;</span><br><span class="line">        this.then(null,onError)</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Finally方法"><a href="#Finally方法" class="headerlink" title="Finally方法"></a>Finally方法</h3><p>在实际应用的时候，我们很容易会碰到这样的场景，不管Promise最后的状态如何，都要执行一些最后的操作。我们把这些操作放到 finally 中，也就是说 finally 注册的函数是与 Promise 的状态无关的，不依赖 Promise 的执行结果。所以我们可以这样写 finally 的逻辑：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function Promise(fn)&#123; </span><br><span class="line">    ...</span><br><span class="line">    this.catch &#x3D; function (onError)&#123;</span><br><span class="line">        this.then(null,onError)</span><br><span class="line">    &#125;</span><br><span class="line">    this.finally &#x3D; function (onDone)&#123;</span><br><span class="line">        this.then(onDone,onDone)</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="resolve-方法和-reject-方法"><a href="#resolve-方法和-reject-方法" class="headerlink" title="resolve 方法和 reject 方法"></a>resolve 方法和 reject 方法</h3><p>实际应用中，我们可以使用 Promise.resolve 和 Promise.reject 方法，用于将于将非 Promise 实例包装为 Promise 实例。如下例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Promise.resolve(&#123;name:&#39;winty&#39;&#125;)</span><br><span class="line">Promise.reject(&#123;name:&#39;winty&#39;&#125;)</span><br><span class="line">&#x2F;&#x2F; 等价于</span><br><span class="line">new Promise(resolve &#x3D;&gt; resolve(&#123;name:&#39;winty&#39;&#125;))</span><br><span class="line">new Promise((resolve,reject) &#x3D;&gt; reject(&#123;name:&#39;winty&#39;&#125;))</span><br></pre></td></tr></table></figure>

<p>这些情况下，Promise.resolve 的入参可能有以下几种情况：</p>
<ul>
<li>无参数 [直接返回一个resolved状态的 Promise 对象]</li>
<li>普通数据对象 [直接返回一个resolved状态的 Promise 对象]</li>
<li>一个Promise实例 [直接返回当前实例]</li>
<li>一个thenable对象(thenable对象指的是具有then方法的对象) [转为 Promise 对象，并立即执行thenable对象的then方法。]</li>
</ul>
<p>基于以上几点，我们可以实现一个 Promise.resolve 方法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">function Promise(fn)&#123; </span><br><span class="line">    ...</span><br><span class="line">    this.resolve &#x3D; function (value)&#123;</span><br><span class="line">        if (value &amp;&amp; value instanceof Promise) &#123;</span><br><span class="line">            return value;</span><br><span class="line">        &#125; else if (value &amp;&amp; typeof value &#x3D;&#x3D;&#x3D; &#39;object&#39; &amp;&amp; typeof value.then &#x3D;&#x3D;&#x3D; &#39;function&#39;)&#123;</span><br><span class="line">            let then &#x3D; value.then;</span><br><span class="line">            return new Promise(resolve &#x3D;&gt; &#123;</span><br><span class="line">                then(resolve);</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125; else if (value) &#123;</span><br><span class="line">            return new Promise(resolve &#x3D;&gt; resolve(value));</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            return new Promise(resolve &#x3D;&gt; resolve());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Promise.reject与Promise.resolve类似，区别在于Promise.reject始终返回一个状态的rejected的Promise实例，而Promise.resolve的参数如果是一个Promise实例的话，返回的是参数对应的Promise实例，所以状态不一 定。 因此，reject 的实现就简单多了，如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"> function Promise(fn)&#123; </span><br><span class="line">     ...</span><br><span class="line">     this.reject &#x3D; function (value)&#123;</span><br><span class="line">         return new Promise(function(resolve, reject) &#123;</span><br><span class="line">	reject(value);</span><br><span class="line">&#125;);</span><br><span class="line">     &#125;</span><br><span class="line">     ...</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<h3 id="Promise-all"><a href="#Promise-all" class="headerlink" title="Promise.all"></a>Promise.all</h3><p>入参是一个 Promise 的实例数组，然后注册一个 then 方法，然后是数组中的 Promise 实例的状态都转为 fulfilled 之后则执行 then 方法。这里主要就是一个计数逻辑，每当一个 Promise 的状态变为 fulfilled 之后就保存该实例返回的数据，然后将计数减一，当计数器变为 0 时，代表数组中所有 Promise 实例都执行完毕。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">function Promise(fn)&#123; </span><br><span class="line">    ...</span><br><span class="line">    this.all &#x3D; function (arr)&#123;</span><br><span class="line">        var args &#x3D; Array.prototype.slice.call(arr);</span><br><span class="line">        return new Promise(function(resolve, reject) &#123;</span><br><span class="line">        	&#x2F;&#x2F; 长度为0返回结果</span><br><span class="line">            if(args.length &#x3D;&#x3D;&#x3D; 0) return resolve([]);</span><br><span class="line">            &#x2F;&#x2F; 剩余参数数组长度</span><br><span class="line">            var remaining &#x3D; args.length;</span><br><span class="line">&#x2F;&#x2F; 参数和值</span><br><span class="line">            function res(i, val) &#123;</span><br><span class="line">                try &#123;</span><br><span class="line">                    if(val &amp;&amp; (typeof val &#x3D;&#x3D;&#x3D; &#39;object&#39; || typeof val &#x3D;&#x3D;&#x3D; &#39;function&#39;)) &#123;</span><br><span class="line">                        var then &#x3D; val.then;</span><br><span class="line">                        &#x2F;&#x2F; 进行参数分析</span><br><span class="line">                        if(typeof then &#x3D;&#x3D;&#x3D; &#39;function&#39;) &#123;</span><br><span class="line">                            then.call(val, function(val) &#123;</span><br><span class="line">                                res(i, val);</span><br><span class="line">                            &#125;, reject);</span><br><span class="line">                            return;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                    args[i] &#x3D; val;</span><br><span class="line">                    if(--remaining &#x3D;&#x3D;&#x3D; 0) &#123;</span><br><span class="line">                        resolve(args);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; catch(ex) &#123;</span><br><span class="line">                    reject(ex);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            &#x2F;&#x2F; 遍历数组中的每个元素</span><br><span class="line">            for(var i &#x3D; 0; i &lt; args.length; i++) &#123;</span><br><span class="line">                res(i, args[i]);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Promise-race"><a href="#Promise-race" class="headerlink" title="Promise.race"></a>Promise.race</h3><p>有了 Promise.all 的理解，Promise.race 理解起来就更容易了。它的入参也是一个 Promise 实例数组，然后其 then 注册的回调方法是数组中的某一个 Promise 的状态变为 fulfilled 的时候就执行。因为 Promise 的状态只能改变一次，那么我们只需要把 Promise.race 中产生的 Promise 对象的 resolve 方法，注入到数组中的每一个 Promise 实例中的回调函数中即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">function Promise(fn)&#123; </span><br><span class="line">    ...</span><br><span class="line">    this.race &#x3D; function(values) &#123;</span><br><span class="line">        return new Promise(function(resolve, reject) &#123;</span><br><span class="line">            for(var i &#x3D; 0, len &#x3D; values.length; i &lt; len; i++) &#123;</span><br><span class="line">                values[i].then(resolve, reject);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>

<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>Promise 源码不过几百行，我们可以从执行结果出发，分析每一步的执行过程，然后思考其作用即可。其中最关键的点就是要理解 then 函数是负责注册回调的，真正的执行是在 Promise 的状态被改变之后。而当 resolve 的入参是一个 Promise 时，要想链式调用起来，就必须调用其 then 方法(then.call),将上一个 Promise 的 resolve 方法注入其回调数组中。</p>
<h3 id="补充说明"><a href="#补充说明" class="headerlink" title="补充说明"></a>补充说明</h3><p>虽然 then 普遍认为是微任务。但是浏览器没办法模拟微任务，目前要么用 setImmediate ，这个也是宏任务，且不兼容的情况下还是用 setTimeout 打底的。还有，promise 的 polyfill (es6-promise) 里用的也是 setTimeout。因此这里就直接用 setTimeout,以宏任务来代替微任务了。</p>
<h3 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h3><ul>
<li><a target="_blank" rel="noopener" href="https://promisesaplus.com/">PromiseA+规范</a></li>
<li><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/58428287">Promise 实现原理精解</a></li>
<li><a target="_blank" rel="noopener" href="https://mengera88.github.io/2017/05/18/Promise%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/">30分钟，让你彻底明白Promise原理</a></li>
</ul>
<h3 id="完整-Promise-模型"><a href="#完整-Promise-模型" class="headerlink" title="完整 Promise 模型"></a>完整 Promise 模型</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br></pre></td><td class="code"><pre><span class="line">function Promise(fn) &#123;</span><br><span class="line">  let state &#x3D; &#39;pending&#39;</span><br><span class="line">  let value &#x3D; null</span><br><span class="line">  const callbacks &#x3D; []</span><br><span class="line"></span><br><span class="line">  this.then &#x3D; function (onFulfilled, onRejected) &#123;</span><br><span class="line">    return new Promise((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">      handle(&#123;</span><br><span class="line">        onFulfilled,</span><br><span class="line">        onRejected,</span><br><span class="line">        resolve,</span><br><span class="line">        reject,</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  this.catch &#x3D; function (onError) &#123;</span><br><span class="line">    return this.then(null, onError)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  this.finally &#x3D; function (onDone) &#123;</span><br><span class="line">    this.then(onDone, onError)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  this.resolve &#x3D; function (value) &#123;</span><br><span class="line">    if (value &amp;&amp; value instanceof Promise) &#123;</span><br><span class="line">      return value</span><br><span class="line">    &#125; if (value &amp;&amp; typeof value &#x3D;&#x3D;&#x3D; &#39;object&#39; &amp;&amp; typeof value.then &#x3D;&#x3D;&#x3D; &#39;function&#39;) &#123;</span><br><span class="line">      const &#123; then &#125; &#x3D; value</span><br><span class="line">      return new Promise((resolve) &#x3D;&gt; &#123;</span><br><span class="line">        then(resolve)</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125; if (value) &#123;</span><br><span class="line">      return new Promise(resolve &#x3D;&gt; resolve(value))</span><br><span class="line">    &#125;</span><br><span class="line">    return new Promise(resolve &#x3D;&gt; resolve())</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  this.reject &#x3D; function (value) &#123;</span><br><span class="line">    return new Promise(((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">      reject(value)</span><br><span class="line">    &#125;))</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  this.all &#x3D; function (arr) &#123;</span><br><span class="line">    const args &#x3D; Array.prototype.slice.call(arr)</span><br><span class="line">    return new Promise(((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">      if (args.length &#x3D;&#x3D;&#x3D; 0) return resolve([])</span><br><span class="line">      let remaining &#x3D; args.length</span><br><span class="line"></span><br><span class="line">      function res(i, val) &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">          if (val &amp;&amp; (typeof val &#x3D;&#x3D;&#x3D; &#39;object&#39; || typeof val &#x3D;&#x3D;&#x3D; &#39;function&#39;)) &#123;</span><br><span class="line">            const &#123; then &#125; &#x3D; val</span><br><span class="line">            if (typeof then &#x3D;&#x3D;&#x3D; &#39;function&#39;) &#123;</span><br><span class="line">              then.call(val, (val) &#x3D;&gt; &#123;</span><br><span class="line">                res(i, val)</span><br><span class="line">              &#125;, reject)</span><br><span class="line">              return</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;</span><br><span class="line">          args[i] &#x3D; val</span><br><span class="line">          if (--remaining &#x3D;&#x3D;&#x3D; 0) &#123;</span><br><span class="line">            resolve(args)</span><br><span class="line">          &#125;</span><br><span class="line">        &#125; catch (ex) &#123;</span><br><span class="line">          reject(ex)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      for (let i &#x3D; 0; i &lt; args.length; i++) &#123;</span><br><span class="line">        res(i, args[i])</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;))</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  this.race &#x3D; function (values) &#123;</span><br><span class="line">    return new Promise(((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">      for (let i &#x3D; 0, len &#x3D; values.length; i &lt; len; i++) &#123;</span><br><span class="line">        values[i].then(resolve, reject)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;))</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  function handle(callback) &#123;</span><br><span class="line">    if (state &#x3D;&#x3D;&#x3D; &#39;pending&#39;) &#123;</span><br><span class="line">      callbacks.push(callback)</span><br><span class="line">      return</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    const cb &#x3D; state &#x3D;&#x3D;&#x3D; &#39;fulfilled&#39; ? callback.onFulfilled : callback.onRejected</span><br><span class="line">    const next &#x3D; state &#x3D;&#x3D;&#x3D; &#39;fulfilled&#39; ? callback.resolve : callback.reject</span><br><span class="line"></span><br><span class="line">    if (!cb) &#123;</span><br><span class="line">      next(value)</span><br><span class="line">      return</span><br><span class="line">    &#125;	</span><br><span class="line">    let ret;</span><br><span class="line">    try &#123;</span><br><span class="line">     ret &#x3D; cb(value)</span><br><span class="line">    &#125; catch (e) &#123;</span><br><span class="line">      callback.reject(e)</span><br><span class="line">    &#125;</span><br><span class="line">	callback.resolve(ret);</span><br><span class="line">  &#125;</span><br><span class="line">  function resolve(newValue) &#123;</span><br><span class="line">    const fn &#x3D; () &#x3D;&gt; &#123;</span><br><span class="line">      if (state !&#x3D;&#x3D; &#39;pending&#39;) return</span><br><span class="line"></span><br><span class="line">      if (newValue &amp;&amp; (typeof newValue &#x3D;&#x3D;&#x3D; &#39;object&#39; || typeof newValue &#x3D;&#x3D;&#x3D; &#39;function&#39;)) &#123;</span><br><span class="line">        const &#123; then &#125; &#x3D; newValue</span><br><span class="line">        if (typeof then &#x3D;&#x3D;&#x3D; &#39;function&#39;) &#123;</span><br><span class="line">          &#x2F;&#x2F; newValue 为新产生的 Promise,此时resolve为上个 promise 的resolve</span><br><span class="line">          &#x2F;&#x2F; 相当于调用了新产生 Promise 的then方法，注入了上个 promise 的resolve 为其回调</span><br><span class="line">          then.call(newValue, resolve, reject)</span><br><span class="line">          return</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      state &#x3D; &#39;fulfilled&#39;</span><br><span class="line">      value &#x3D; newValue</span><br><span class="line">      handelCb()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    setTimeout(fn, 0)</span><br><span class="line">  &#125;</span><br><span class="line">  function reject(error) &#123;</span><br><span class="line">    const fn &#x3D; () &#x3D;&gt; &#123;</span><br><span class="line">      if (state !&#x3D;&#x3D; &#39;pending&#39;) return</span><br><span class="line"></span><br><span class="line">      if (error &amp;&amp; (typeof error &#x3D;&#x3D;&#x3D; &#39;object&#39; || typeof error &#x3D;&#x3D;&#x3D; &#39;function&#39;)) &#123;</span><br><span class="line">        const &#123; then &#125; &#x3D; error</span><br><span class="line">        if (typeof then &#x3D;&#x3D;&#x3D; &#39;function&#39;) &#123;</span><br><span class="line">          then.call(error, resolve, reject)</span><br><span class="line">          return</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      state &#x3D; &#39;rejected&#39;</span><br><span class="line">      value &#x3D; error</span><br><span class="line">      handelCb()</span><br><span class="line">    &#125;</span><br><span class="line">    setTimeout(fn, 0)</span><br><span class="line">  &#125;</span><br><span class="line">  function handelCb() &#123;</span><br><span class="line">    while (callbacks.length) &#123;</span><br><span class="line">      const fn &#x3D; callbacks.shift()</span><br><span class="line">      handle(fn)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  try &#123;</span><br><span class="line">  fn(resolve, reject)</span><br><span class="line">  &#125; catch(ex) &#123;</span><br><span class="line">	reject(ex);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="17-Generators原理"><a href="#17-Generators原理" class="headerlink" title="17.Generators原理"></a>17.Generators原理</h1><p>随着 Javascript 语言的发展，ES6 规范为我们带来了许多新的内容，其中生成器 Generators 是一项重要的特性。利用这一特性，我们可以简化迭代器的创建，更加令人兴奋的，是 Generators 允许我们在函数执行过程中暂停、并在将来某一时刻恢复执行。这一特性改变了以往函数必须执行完成才返回的特点，将这一特性应用到异步代码编写中，可以有效的简化异步方法的写法，同时避免陷入回调地狱。</p>
<p>本重点探讨 Generators 运行机制及在 ES5 的实现原理。</p>
<h2 id="1-Generators-简单介绍"><a href="#1-Generators-简单介绍" class="headerlink" title="1.Generators 简单介绍"></a><strong>1.Generators 简单介绍</strong></h2><p>一个简单的 Generator 函数示例</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">example</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">2</span>;</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">3</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> iter=example();</span><br><span class="line">iter.next();<span class="comment">//&#123;value:1，done:false&#125;</span></span><br><span class="line">iter.next();<span class="comment">//&#123;value:2，done:false&#125;</span></span><br><span class="line">iter.next();<span class="comment">//&#123;value:3，done:false&#125;</span></span><br><span class="line">iter.next();<span class="comment">//&#123;value:undefined，done:true&#125;</span></span><br></pre></td></tr></table></figure>

<p>​    上述代码中定义了一个生成器函数，当调用生成器函数 example() 时，并非立即执行该函数，而是返回一个生成器对象。每当调用生成器对象的.next() 方法时，函数将运行到下一个 yield 表达式，返回表达式结果并暂停自身。当抵达生成器函数的末尾时，返回结果中 done 的值为 true，value 的值为 undefined。我们将上述 example() 函数称之为生成器函数，与普通函数相比二者有如下区别</p>
<ul>
<li>普通函数使用 function 声明，生成器函数用 function*声明</li>
<li>普通函数使用 return 返回值，生成器函数使用 yield 返回值</li>
<li>普通函数是 run to completion 模式，即普通函数开始执行后，会一直执行到该函数所有语句完成，在此期间别的代码语句是不会被执行的；生成器函数是 run-pause-run 模式，即生成器函数可以在函数运行中被暂停一次或多次，并且在后面再恢复执行，在暂停期间允许其他代码语句被执行</li>
</ul>
<h2 id="2-Generators-in-C"><a href="#2-Generators-in-C" class="headerlink" title="2.Generators in C#"></a><strong>2.Generators in C#</strong></h2><p>生成器不是一个新的概念，我最初接触这一概念是在学习使用 C#时。C#从 2.0 版本便引入了 yield 关键字，使得我们可以更简单的创建枚举数和可枚举类型。不同的是 C#中未将其命名为生成器 Generators，而将其称之为迭代器。</p>
<p>本文不会介绍 C#中可枚举类 IEnumerable 和枚举数 IEnumerator 内容，如需了解推荐阅读《C#4.0 图解教程》相关章节。</p>
<p>2.1 C#迭代器介绍</p>
<p>让我们先看一个示例，下面方法声明实现了一个产生和返回枚举数的迭代器</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public IEnumerable &lt;int&gt; Example()</span><br><span class="line">&#123;</span><br><span class="line">		yield return 1;</span><br><span class="line">		yield return 2;</span><br><span class="line">		yield return 3;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>方法定义与 ES6 Generators 定义很接近，定义中声明返回了一个 int 类型的泛型可枚举类型，方法体内通过 yield return 语句返回值并将自身暂停执行。</p>
<p>使用迭代器来创建可枚举类型的类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">class YieldClass</span><br><span class="line">&#123;</span><br><span class="line">    public IEnumerable&lt;int&gt; Example()&#x2F;&#x2F;迭代器</span><br><span class="line">    &#123;</span><br><span class="line">	yield return 1;</span><br><span class="line">	yield return 2;</span><br><span class="line">	yield return 3;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">class Program</span><br><span class="line">&#123;</span><br><span class="line">    static void Main()</span><br><span class="line">    &#123;</span><br><span class="line">	YieldClass yc&#x3D;new YieldClass ();</span><br><span class="line">	foreach(var a in yc.Example())</span><br><span class="line">		Console.WriteLine(a);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述代码会产生如下输入</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td></tr></table></figure>

<p>2.2 C#迭代器原理</p>
<p>在.Net 中，yield 并不是.Net runtime 的特性，而是一个语法糖，代码编译时，这一语法糖会被 C#编译器编译成简单的 IL 代码。</p>
<p>继续研究上述示例，通过 Reflector 反编译工具可以看到，编译器为我们生成了一个带有如下声明的内部类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">[CompilerGenerated]</span><br><span class="line">private sealed class YieldEnumerator : </span><br><span class="line">   IEnumerable&lt;object&gt;, IEnumerator&lt;object&gt;</span><br><span class="line">&#123;</span><br><span class="line">    &#x2F;&#x2F; Fields字段</span><br><span class="line">    private int state;</span><br><span class="line">    private int current;</span><br><span class="line">    public YieldClass owner;</span><br><span class="line">    private int initialThreadId;</span><br><span class="line"> </span><br><span class="line">    &#x2F;&#x2F; Methods方法</span><br><span class="line">    [DebuggerHidden]</span><br><span class="line">    public YieldEnumerator(int state);</span><br><span class="line">    private bool MoveNext();</span><br><span class="line">    [DebuggerHidden]</span><br><span class="line">    IEnumerator&lt;int&gt; IEnumerable&lt;int&gt;.GetEnumerator();</span><br><span class="line">    [DebuggerHidden]</span><br><span class="line">    IEnumerator IEnumerable.GetEnumerator();</span><br><span class="line">    [DebuggerHidden]</span><br><span class="line">    void IEnumerator.Reset();</span><br><span class="line">    void IDisposable.Dispose();</span><br><span class="line"> </span><br><span class="line">    &#x2F;&#x2F; Properties属性</span><br><span class="line">    object IEnumerator&lt;object&gt;.Current </span><br><span class="line">    &#123; [DebuggerHidden] get; &#125;</span><br><span class="line"> </span><br><span class="line">    object IEnumerator.Current </span><br><span class="line">    &#123; [DebuggerHidden] get; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>原始的 Example() 方法仅返回一个 YieldEnumerator 的实例，并将初始状态-2 传递给它自身和其引用者，每一个迭代器保存一个状态指示</p>
<ul>
<li>-2：初始化为可迭代类 Enumerable</li>
<li>-1: 迭代结束</li>
<li>0: 初始化为迭代器 Enumerator</li>
<li>1-n: 原始 Example() 方法中的 yield return 索引值</li>
</ul>
<p>Example() 方法中代码被转换为 YieldingEnumerator.MoveNext()，在我们的示例中转换后代码如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">bool MoveNext()</span><br><span class="line">&#123;</span><br><span class="line">    switch (state)</span><br><span class="line">    &#123;</span><br><span class="line">        case 0:</span><br><span class="line">            state &#x3D; -1;</span><br><span class="line">            current &#x3D; 1;</span><br><span class="line">            state &#x3D; 1;</span><br><span class="line">            return true;</span><br><span class="line">        case 1:</span><br><span class="line">            state &#x3D; -1;</span><br><span class="line">            current &#x3D; 2;</span><br><span class="line">            state &#x3D; 2;</span><br><span class="line">            return true;</span><br><span class="line">        case 2:</span><br><span class="line">            state &#x3D; -1;</span><br><span class="line">            current &#x3D; 3;</span><br><span class="line">            state &#x3D; 3;</span><br><span class="line">            return true;</span><br><span class="line">        case 3:</span><br><span class="line">            state &#x3D; -1;</span><br><span class="line">            break;</span><br><span class="line">    &#125;</span><br><span class="line">    return false;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>利用上述的代码转换，编译器为我们生成了一个状态机，正是基于这一状态机模型，实现了 yield 关键字的特性。</p>
<p>迭代器状态机模型可如下图所示</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144900.png" alt="img"></p>
<ul>
<li>Before 为迭代器初始状态</li>
<li>Running 为调用 MoveNext 后进入这个状态。在这个状态，枚举数检测并设置下一项的位置。遇到 yield return、yield break 或者迭代结束时，退出该状态</li>
<li>Suspended 为状态机等待下次调用 MoveNext 的状态</li>
<li>After 为迭代结束的状态</li>
</ul>
<p><strong>3.Generators in Javascript</strong></p>
<p>通过阅读上文，我们了解了 Generator 在 C#中的使用，并且通过查看编译器生成的 IL 代码，得知编译器会生成一个内部类来保存上下文信息，然后将 yield return 表达式转换成 switch case，通过状态机模式实现 yield 关键字的特性。</p>
<p>3.1 Javascript Generators 原理浅析</p>
<p>yield 关键字在 Javascript 中如何实现呢？</p>
<p>首先，生成器不是线程。支持线程的语言中，多段不同的代码可以在同一时候运行，这经常会导致资源竞争，使用得当会有不错的性能提升。生成器则完全不同，Javascript 执行引擎仍然是一个基于事件循环的单线程环境，当生成器运行的时候，它会在叫做 caller 的同一个线程中运行。执行的顺序是有序、确定的，并且永远不会产生并发。不同于系统的线程，生成器只会在其内部用到 yield 的时候才会被挂起。</p>
<p>既然生成器并非由引擎从底层提供额外的支持，我们可以沿用上文在 C#中对 yield 特性的原理探究的经验，将生成器视为一个语法糖，用一个辅助工具将生成器函数转换为普通的 Javascript 代码，在经过转换的代码中，有两个关键点，一是要保存函数的上下文信息，二是实现一个完善的迭代方法，使得多个 yield 表达式按序执行，从而实现生成器的特性。</p>
<p>3.2 How Generators work in ES5</p>
<p><a target="_blank" rel="noopener" href="https://facebook.github.io/regenerator/">Regenerator</a> 工具已经实现了上述思路，借助 Regenerator 工具，我们已经可以在原生 ES5 中使用生成器函数，本节我们来分析 Regenerator 实现方式以深入理解 Generators 运行原理。</p>
<p>通过<a target="_blank" rel="noopener" href="http://babeljs.io/repl/">这个在线地址</a>可以方便的查看经过转换后的代码，仍然以文章初始为例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">function* example() &#123;</span><br><span class="line">  yield 1;</span><br><span class="line">  yield 2;</span><br><span class="line">  yield 3;</span><br><span class="line">&#125;</span><br><span class="line">var iter&#x3D;example();</span><br><span class="line">iter.next();</span><br></pre></td></tr></table></figure>

<p>经过转换后为</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">var marked0$0 &#x3D; [example].map(regeneratorRuntime.mark);</span><br><span class="line">function example() &#123;</span><br><span class="line">  return regeneratorRuntime.wrap(function example$(context$1$0) &#123;</span><br><span class="line">    while (1) switch (context$1$0.prev &#x3D; context$1$0.next) &#123;</span><br><span class="line">      case 0:</span><br><span class="line">        context$1$0.next &#x3D; 2;</span><br><span class="line">        return 1;</span><br><span class="line"> </span><br><span class="line">      case 2:</span><br><span class="line">        context$1$0.next &#x3D; 4;</span><br><span class="line">        return 2;</span><br><span class="line"> </span><br><span class="line">      case 4:</span><br><span class="line">        context$1$0.next &#x3D; 6;</span><br><span class="line">        return 3;</span><br><span class="line"> </span><br><span class="line">      case 6:</span><br><span class="line">      case &quot;end&quot;:</span><br><span class="line">        return context$1$0.stop();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;, marked0$0[0], this);</span><br><span class="line">&#125;</span><br><span class="line">var iter &#x3D; example();</span><br><span class="line">iter.next();</span><br></pre></td></tr></table></figure>

<p>从转换后的代码中可以看到，与 C#编译器对 yield return 表达式的转换相似，Regenerator 将生成器函数中的 yield 表达式重写为 switch case，同时，在每个 case 中使用 context$1$0 来保存函数当前的上下文状态。</p>
<p>switch case 之外，迭代器函数 example 被 regeneratorRuntime.mark 包装，返回一个被 regeneratorRuntime.wrap 包装的迭代器对象。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">runtime.mark &#x3D; function(genFun) &#123;</span><br><span class="line">  if (Object.setPrototypeOf) &#123;</span><br><span class="line">    Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);</span><br><span class="line">  &#125; else &#123;</span><br><span class="line">    genFun.__proto__ &#x3D; GeneratorFunctionPrototype;</span><br><span class="line">  &#125;</span><br><span class="line">  genFun.prototype &#x3D; Object.create(Gp);</span><br><span class="line">  return genFun;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>通过 mark 包装，将 example 包装成如下对象</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144524.png" alt="example"></p>
<p>当调用生成器函数 example() 时，返回一个被 wrap 函数包装后的迭代器对象</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">runtime.wrap&#x3D;function (innerFn, outerFn, self, tryLocsList) &#123;</span><br><span class="line">  &#x2F;&#x2F; If outerFn provided, then outerFn.prototype instanceof Generator.</span><br><span class="line">  var generator &#x3D; Object.create((outerFn || Generator).prototype);</span><br><span class="line">  var context &#x3D; new Context(tryLocsList || []);</span><br><span class="line"> </span><br><span class="line">  &#x2F;&#x2F; The ._invoke method unifies the implementations of the .next,</span><br><span class="line">  &#x2F;&#x2F; .throw, and .return methods.</span><br><span class="line">  generator._invoke &#x3D; makeInvokeMethod(innerFn, self, context);</span><br><span class="line"> </span><br><span class="line">  return generator;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>返回的迭代器对象如下所示</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210419144540.png" alt="iter"></p>
<p>当调用迭代器对象 iter.next() 方法时，因为有如下代码，所以会执行_invoke 方法，而根据前面 wrap 方法代码可知，最终是调用了迭代器对象的 makeInvokeMethod (innerFn, self, context); 方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; Helper for defining the .next, .throw, and .return methods of the</span><br><span class="line">&#x2F;&#x2F; Iterator interface in terms of a single ._invoke method.</span><br><span class="line">function defineIteratorMethods(prototype) &#123;</span><br><span class="line">  [&quot;next&quot;, &quot;throw&quot;, &quot;return&quot;].forEach(function(method) &#123;</span><br><span class="line">    prototype[method] &#x3D; function(arg) &#123;</span><br><span class="line">      return this._invoke(method, arg);</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>makeInvokeMethod 方法内容较多，这里选取部分分析。首先，我们发现生成器将自身状态初始化为“Suspended Start”</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">function makeInvokeMethod(innerFn, self, context) &#123;</span><br><span class="line">  var state &#x3D; GenStateSuspendedStart;</span><br><span class="line"> </span><br><span class="line">  return function invoke(method, arg) &#123;</span><br></pre></td></tr></table></figure>

<p>makeInvokeMethod 返回 invoke 函数，当我们执行.next 方法时，实际调用的是 invoke 方法中的下面语句</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var record &#x3D; tryCatch(innerFn, self, context);</span><br></pre></td></tr></table></figure>

<p>这里 tryCatch 方法中 fn 为经过转换后的 example$方法，arg 为上下文对象 context, 因为 invoke 函数内部对 context 的引用形成闭包引用，所以 context 上下文得以在迭代期间一直保持。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">function tryCatch(fn, obj, arg) &#123;</span><br><span class="line">  try &#123;</span><br><span class="line">    return &#123; type: &quot;normal&quot;, arg: fn.call(obj, arg) &#125;;</span><br><span class="line">  &#125; catch (err) &#123;</span><br><span class="line">    return &#123; type: &quot;throw&quot;, arg: err &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>tryCatch 方法会实际调用 example$方法，进入转换后的 switch case, 执行代码逻辑。如果得到的结果是一个普通类型的值，我们将它包装成一个可迭代对象格式，并且更新生成器状态至 GenStateCompleted 或者 GenStateSuspendedYield</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">var record &#x3D; tryCatch(innerFn, self, context);</span><br><span class="line">        if (record.type &#x3D;&#x3D;&#x3D; &quot;normal&quot;) &#123;</span><br><span class="line">          &#x2F;&#x2F; If an exception is thrown from innerFn, we leave state &#x3D;&#x3D;&#x3D;</span><br><span class="line">          &#x2F;&#x2F; GenStateExecuting and loop back for another invocation.</span><br><span class="line">          state &#x3D; context.done</span><br><span class="line">            ? GenStateCompleted</span><br><span class="line">            : GenStateSuspendedYield;</span><br><span class="line"> </span><br><span class="line">          var info &#x3D; &#123;</span><br><span class="line">            value: record.arg,</span><br><span class="line">            done: context.done</span><br><span class="line">          &#125;;</span><br></pre></td></tr></table></figure>

<p><strong>4. 总结</strong></p>
<p>通过对 Regenerator 转换后的生成器代码及工具源码分析，我们探究了生成器的运行原理。Regenerator 通过工具函数将生成器函数包装，为其添加如 next/return 等方法。同时也对返回的生成器对象进行包装，使得对 next 等方法的调用，最终进入由 switch case 组成的状态机模型中。除此之外，利用闭包技巧，保存生成器函数上下文信息。</p>
<p>上述过程与 C#中 yield 关键字的实现原理基本一致，都采用了编译转换思路，运用状态机模型，同时保存函数上下文信息，最终实现了新的 yield 关键字带来的新的语言特性。</p>
<p>参考文章</p>
<p>1.<a target="_blank" rel="noopener" href="https://davidwalsh.name/es6-generators">ES6 Generators:Complete Series 系列文章</a></p>
<p>2.<a target="_blank" rel="noopener" href="http://www.infoq.com/cn/articles/es6-in-depth-generators">深入浅出 ES6 Generators</a></p>
<p>3.<a target="_blank" rel="noopener" href="http://www.ruanyifeng.com/blog/2015/04/generator.html">《深入掌握 ECMAScript 6 异步编程》系列文章</a></p>
<p>4.<a target="_blank" rel="noopener" href="http://x-team.com/2015/04/generators-work/">ES6 Generators:How do they work?</a></p>
<p>5.<a target="_blank" rel="noopener" href="https://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/">Behind the scenes of the C# yield keyword</a></p>

    </div>

    
    
    
      
<div>
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
</div>
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E9%9D%A2%E8%AF%95/" rel="tag"><i class="fa fa-tag"></i> 面试</a>
              <a href="/tags/javascript/" rel="tag"><i class="fa fa-tag"></i> javascript</a>
              <a href="/tags/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/" rel="tag"><i class="fa fa-tag"></i> 前端基础</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/02/10/js%E5%87%BD%E6%95%B0%E6%89%8B%E5%86%99/" rel="prev" title="js函数手写">
      <i class="fa fa-chevron-left"></i> js函数手写
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/02/25/%E5%89%8D%E7%AB%AF%E6%80%A7%E8%83%BD/" rel="next" title="前端性能">
      前端性能 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%8E%9F%E5%9E%8B%E9%93%BE"><span class="nav-text">1.原型链</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E5%88%9B%E5%BB%BA%E5%AF%B9%E8%B1%A1"><span class="nav-text">1.1 构造函数创建对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-prototype"><span class="nav-text">1.2 prototype</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-proto"><span class="nav-text">1.3 __proto__</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4-constructor"><span class="nav-text">1.4 constructor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-%E5%AE%9E%E4%BE%8B%E4%B8%8E%E5%8E%9F%E5%9E%8B"><span class="nav-text">1.5 实例与原型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-6-%E5%8E%9F%E5%9E%8B%E7%9A%84%E5%8E%9F%E5%9E%8B"><span class="nav-text">1.6 原型的原型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-7-%E5%8E%9F%E5%9E%8B%E9%93%BE"><span class="nav-text">1.7 原型链</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A1%A5%E5%85%85"><span class="nav-text">补充</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#constructor-NaN"><span class="nav-text">constructor</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#proto"><span class="nav-text">__proto__</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%9C%9F%E7%9A%84%E6%98%AF%E7%BB%A7%E6%89%BF%E5%90%97%EF%BC%9F"><span class="nav-text">真的是继承吗？</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E7%BB%A7%E6%89%BF"><span class="nav-text">2.继承</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E5%8E%9F%E5%9E%8B%E9%93%BE%E7%BB%A7%E6%89%BF"><span class="nav-text">2.1 原型链继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E5%80%9F%E7%94%A8%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0-%E7%BB%8F%E5%85%B8%E7%BB%A7%E6%89%BF"><span class="nav-text">2.2 借用构造函数(经典继承)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-%E7%BB%84%E5%90%88%E7%BB%A7%E6%89%BF"><span class="nav-text">2.3 组合继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-%E5%8E%9F%E5%9E%8B%E5%BC%8F%E7%BB%A7%E6%89%BF"><span class="nav-text">2.4 原型式继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-5-%E5%AF%84%E7%94%9F%E5%BC%8F%E7%BB%A7%E6%89%BF"><span class="nav-text">2.5 寄生式继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-6-%E5%AF%84%E7%94%9F%E7%BB%84%E5%90%88%E5%BC%8F%E7%BB%A7%E6%89%BF"><span class="nav-text">2.6 寄生组合式继承</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-%E4%BD%9C%E7%94%A8%E5%9F%9F%E9%93%BE"><span class="nav-text">3.作用域链</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-%E5%AE%9A%E4%B9%89"><span class="nav-text">3.1 定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-%E5%87%BD%E6%95%B0%E5%88%9B%E5%BB%BA"><span class="nav-text">3.2 函数创建</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-%E5%87%BD%E6%95%B0%E6%BF%80%E6%B4%BB"><span class="nav-text">3.3 函数激活</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-4-%E6%8C%89%E7%85%A7%E6%AD%A5%E9%AA%A4%E5%88%86%E6%9E%90"><span class="nav-text">3.4 按照步骤分析</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-%E9%97%AD%E5%8C%85"><span class="nav-text">4.闭包</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-%E5%AE%9A%E4%B9%89"><span class="nav-text">4.1 定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-%E5%88%86%E6%9E%90"><span class="nav-text">4.2 分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-%E5%BF%85%E5%88%B7%E9%A2%98"><span class="nav-text">4.3 必刷题</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-%E5%8F%98%E9%87%8F%E5%AF%B9%E8%B1%A1"><span class="nav-text">5.变量对象</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1-%E5%8F%98%E9%87%8F%E5%AF%B9%E8%B1%A1"><span class="nav-text">5.1 变量对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-2-%E5%85%A8%E5%B1%80%E4%B8%8A%E4%B8%8B%E6%96%87"><span class="nav-text">5.2 全局上下文</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-3-%E5%87%BD%E6%95%B0%E4%B8%8A%E4%B8%8B%E6%96%87"><span class="nav-text">5.3 函数上下文</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-4-%E6%89%A7%E8%A1%8C%E8%BF%87%E7%A8%8B"><span class="nav-text">5.4 执行过程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-4-1-%E8%BF%9B%E5%85%A5%E6%89%A7%E8%A1%8C%E4%B8%8A%E4%B8%8B%E6%96%87"><span class="nav-text">5.4.1 进入执行上下文</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-4-2-%E4%BB%A3%E7%A0%81%E6%89%A7%E8%A1%8C"><span class="nav-text">5.4.2 代码执行</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-5-%E6%80%9D%E8%80%83%E9%A2%98"><span class="nav-text">5.5 思考题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E7%AC%AC%E4%B8%80%E9%A2%98"><span class="nav-text">1.第一题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E7%AC%AC%E4%BA%8C%E9%A2%98"><span class="nav-text">2.第二题</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#6-%E4%BB%8EECMAScript%E8%A7%84%E8%8C%83%E8%A7%A3%E8%AF%BBthis"><span class="nav-text">6.从ECMAScript规范解读this</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#6-1-Types"><span class="nav-text">6.1 Types</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-2-Reference"><span class="nav-text">6.2 Reference</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-3-GetValue"><span class="nav-text">6.3 GetValue</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-4-%E5%A6%82%E4%BD%95%E7%A1%AE%E5%AE%9Athis%E7%9A%84%E5%80%BC"><span class="nav-text">6.4 如何确定this的值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-5-%E5%85%B7%E4%BD%93%E5%88%86%E6%9E%90"><span class="nav-text">6.5 具体分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-5-1-foo-bar"><span class="nav-text">6.5.1 foo.bar()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-5-2-foo-bar"><span class="nav-text">6.5.2 (foo.bar)()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-5-3-foo-bar-foo-bar"><span class="nav-text">6.5.3 (foo.bar &#x3D; foo.bar)()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-5-4-false-foo-bar"><span class="nav-text">6.5.4 (false || foo.bar)()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-5-5-foo-bar-foo-bar"><span class="nav-text">6.5.5 (foo.bar, foo.bar)()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-5-6-%E6%8F%AD%E6%99%93%E7%BB%93%E6%9E%9C"><span class="nav-text">6.5.6 揭晓结果</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A1%A5%E5%85%85-1"><span class="nav-text">补充</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-6-%E5%A4%9A%E8%AF%B4%E4%B8%80%E5%8F%A5"><span class="nav-text">6.6 多说一句</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#7-%E7%AB%8B%E5%8D%B3%E6%89%A7%E8%A1%8C%E5%87%BD%E6%95%B0"><span class="nav-text">7.立即执行函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%83%E6%98%AF%E4%BB%80%E4%B9%88"><span class="nav-text">它是什么</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%83%E7%9A%84%E6%A0%B8%E5%BF%83"><span class="nav-text">它的核心</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%EF%BC%8C%E5%9C%86%E6%8B%AC%E5%8F%B7%EF%BC%8C%E9%94%99%E8%AF%AF"><span class="nav-text">函数，圆括号，错误</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AB%8B%E5%8D%B3%E6%89%A7%E8%A1%8C%E5%87%BD%E6%95%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F%EF%BC%88IIFE%EF%BC%89"><span class="nav-text">立即执行函数表达式（IIFE）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E%E6%8B%AC%E5%8F%B7%E7%9A%84%E9%87%8D%E8%A6%81%E7%AC%94%E8%AE%B0"><span class="nav-text">关于括号的重要笔记</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BF%9D%E5%AD%98%E9%97%AD%E5%8C%85%E7%9A%84%E7%8A%B6%E6%80%81"><span class="nav-text">保存闭包的状态</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%87%AA%E6%89%A7%E8%A1%8C%E5%8C%BF%E5%90%8D%E5%87%BD%E6%95%B0-%E2%80%9CSelf-executing-anonymous-function%E2%80%9D-%E6%9C%89%E4%BB%80%E4%B9%88%E9%97%AE%E9%A2%98%E5%91%A2%EF%BC%9F"><span class="nav-text">自执行匿名函数(“Self-executing anonymous function”)有什么问题呢？</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%80%E5%90%8E%EF%BC%9A%E6%A8%A1%E5%9D%97%E6%A8%A1%E5%BC%8F"><span class="nav-text">最后：模块模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#8-instanceof-%E5%92%8C-typeof-%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="nav-text">8.instanceof 和 typeof 的实现原理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#8-1-typeof-%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="nav-text">8.1 typeof 实现原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-2-instanceof-%E6%93%8D%E4%BD%9C%E7%AC%A6%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="nav-text">8.2 instanceof 操作符的实现原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-3-%E6%80%BB%E7%BB%93"><span class="nav-text">8.3 总结</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#9-bind%E5%AE%9E%E7%8E%B0"><span class="nav-text">9.bind实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9A%E4%B9%89"><span class="nav-text">定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%94%E5%9B%9E%E5%87%BD%E6%95%B0%E7%9A%84%E6%A8%A1%E6%8B%9F%E5%AE%9E%E7%8E%B0"><span class="nav-text">返回函数的模拟实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BC%A0%E5%8F%82%E7%9A%84%E6%A8%A1%E6%8B%9F%E5%AE%9E%E7%8E%B0"><span class="nav-text">传参的模拟实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E6%95%88%E6%9E%9C%E7%9A%84%E6%A8%A1%E6%8B%9F%E5%AE%9E%E7%8E%B0"><span class="nav-text">构造函数效果的模拟实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E6%95%88%E6%9E%9C%E7%9A%84%E4%BC%98%E5%8C%96%E5%AE%9E%E7%8E%B0"><span class="nav-text">构造函数效果的优化实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89%E4%B8%AA%E5%B0%8F%E9%97%AE%E9%A2%98"><span class="nav-text">三个小问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%80%E7%BB%88%E4%BB%A3%E7%A0%81"><span class="nav-text">最终代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%9D%A2%E8%AF%95%E5%A4%9F%E7%94%A8%E7%89%88"><span class="nav-text">面试够用版</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#10-call%E5%92%8Capply"><span class="nav-text">10.call和apply</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#call-%E5%92%8C-apply-%E7%9A%84%E5%85%B1%E5%90%8C%E7%82%B9"><span class="nav-text">call 和 apply 的共同点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#call-%E5%92%8C-apply-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-text">call 和 apply 的区别</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#call-%E7%9A%84%E5%86%99%E6%B3%95"><span class="nav-text">call 的写法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#apply-%E7%9A%84%E5%86%99%E6%B3%95"><span class="nav-text">apply 的写法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E7%B1%BB%E6%95%B0%E7%BB%84%EF%BC%9F"><span class="nav-text">什么是类数组？</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#call-%E5%92%8C-apply-%E7%9A%84%E7%94%A8%E9%80%94"><span class="nav-text">call 和 apply 的用途</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#call-%E7%9A%84%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text">call 的使用场景</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#apply-%E7%9A%84%E4%B8%80%E4%BA%9B%E5%A6%99%E7%94%A8"><span class="nav-text">apply 的一些妙用</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%89%8B%E5%86%99apply%E5%92%8Cbind"><span class="nav-text">手写apply和bind</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#11-%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96"><span class="nav-text">11.函数柯里化</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9A%E4%B9%89-1"><span class="nav-text">定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%94%A8%E9%80%94"><span class="nav-text">用途</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC%E4%B8%80%E7%89%88"><span class="nav-text">第一版</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC%E4%BA%8C%E7%89%88"><span class="nav-text">第二版</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9B%B4%E6%98%93%E6%87%82%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="nav-text">更易懂的实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC%E4%B8%89%E7%89%88"><span class="nav-text">第三版</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%9D%A2%E8%AF%95%E5%A4%9F%E7%94%A8%E7%89%88-1"><span class="nav-text">面试够用版</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#12-V8%E5%BC%95%E6%93%8E%E7%9A%84%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6"><span class="nav-text">12.V8引擎的垃圾回收</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%95%E8%A8%80"><span class="nav-text">引言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E4%B8%BA%E4%BD%95%E9%9C%80%E8%A6%81%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6"><span class="nav-text">1、为何需要垃圾回收</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81V8%E5%BC%95%E6%93%8E%E7%9A%84%E5%86%85%E5%AD%98%E9%99%90%E5%88%B6"><span class="nav-text">2、V8引擎的内存限制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E3%80%81V8%E7%9A%84%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AD%96%E7%95%A5"><span class="nav-text">3、V8的垃圾回收策略</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-V8%E7%9A%84%E5%86%85%E5%AD%98%E7%BB%93%E6%9E%84"><span class="nav-text">3.1 V8的内存结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-%E6%96%B0%E7%94%9F%E4%BB%A3"><span class="nav-text">3.2 新生代</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-%E5%AF%B9%E8%B1%A1%E6%99%8B%E5%8D%87"><span class="nav-text">3.3 对象晋升</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-%E8%80%81%E7%94%9F%E4%BB%A3"><span class="nav-text">3.4 老生代</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E3%80%81%E5%A6%82%E4%BD%95%E9%81%BF%E5%85%8D%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F"><span class="nav-text">4、如何避免内存泄漏</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-%E5%B0%BD%E5%8F%AF%E8%83%BD%E5%B0%91%E5%9C%B0%E5%88%9B%E5%BB%BA%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F"><span class="nav-text">4.1 尽可能少地创建全局变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-%E6%89%8B%E5%8A%A8%E6%B8%85%E9%99%A4%E5%AE%9A%E6%97%B6%E5%99%A8"><span class="nav-text">4.2 手动清除定时器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-%E5%B0%91%E7%94%A8%E9%97%AD%E5%8C%85"><span class="nav-text">4.3 少用闭包</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-4-%E6%B8%85%E9%99%A4DOM%E5%BC%95%E7%94%A8"><span class="nav-text">4.4 清除DOM引用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-5-%E5%BC%B1%E5%BC%95%E7%94%A8"><span class="nav-text">4.5 弱引用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5%E3%80%81%E6%80%BB%E7%BB%93"><span class="nav-text">5、总结</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#13-%E6%B5%AE%E7%82%B9%E6%95%B0%E7%B2%BE%E5%BA%A6"><span class="nav-text">13.浮点数精度</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%95%B0%E5%AD%97%E7%B1%BB%E5%9E%8B"><span class="nav-text">数字类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B5%AE%E7%82%B9%E6%95%B0%E8%BD%AC%E4%BA%8C%E8%BF%9B%E5%88%B6"><span class="nav-text">浮点数转二进制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B5%AE%E7%82%B9%E6%95%B0%E7%9A%84%E5%AD%98%E5%82%A8"><span class="nav-text">浮点数的存储</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B5%AE%E7%82%B9%E6%95%B0%E7%9A%84%E8%BF%90%E7%AE%97"><span class="nav-text">浮点数的运算</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B6%E4%BB%96"><span class="nav-text">其他</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#14-new"><span class="nav-text">14.new</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9A%E4%B9%89-2"><span class="nav-text">定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9D%E6%AD%A5%E5%AE%9E%E7%8E%B0"><span class="nav-text">初步实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%94%E5%9B%9E%E5%80%BC%E6%95%88%E6%9E%9C%E5%AE%9E%E7%8E%B0"><span class="nav-text">返回值效果实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#15-Event-Loop%EF%BC%88%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%EF%BC%89%E6%9C%BA%E5%88%B6"><span class="nav-text">15.Event Loop（事件循环）机制</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%89%8D%E8%A8%80-1"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%AD%A3%E6%96%87"><span class="nav-text">正文</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E7%8E%AF%E5%A2%83%E4%B8%8Bjs%E5%BC%95%E6%93%8E%E7%9A%84%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%9C%BA%E5%88%B6"><span class="nav-text">浏览器环境下js引擎的事件循环机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E6%89%A7%E8%A1%8C%E6%A0%88%E4%B8%8E%E4%BA%8B%E4%BB%B6%E9%98%9F%E5%88%97"><span class="nav-text">1.执行栈与事件队列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-macro-task%E4%B8%8Emicro-task"><span class="nav-text">2.macro task与micro task</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#node%E7%8E%AF%E5%A2%83%E4%B8%8B%E7%9A%84%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%9C%BA%E5%88%B6"><span class="nav-text">node环境下的事件循环机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E4%B8%8E%E6%B5%8F%E8%A7%88%E5%99%A8%E7%8E%AF%E5%A2%83%E6%9C%89%E4%BD%95%E4%B8%8D%E5%90%8C"><span class="nav-text">1.与浏览器环境有何不同?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%A8%A1%E5%9E%8B"><span class="nav-text">2.事件循环模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E5%90%84%E9%98%B6%E6%AE%B5%E8%AF%A6%E8%A7%A3"><span class="nav-text">3.事件循环各阶段详解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#poll%E9%98%B6%E6%AE%B5"><span class="nav-text">poll阶段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#check%E9%98%B6%E6%AE%B5"><span class="nav-text">check阶段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#close%E9%98%B6%E6%AE%B5"><span class="nav-text">close阶段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#timer%E9%98%B6%E6%AE%B5"><span class="nav-text">timer阶段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#I-O-callback%E9%98%B6%E6%AE%B5"><span class="nav-text">I&#x2F;O callback阶段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-process-nextTick-setTimeout%E4%B8%8EsetImmediate%E7%9A%84%E5%8C%BA%E5%88%AB%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text">4.process.nextTick,setTimeout与setImmediate的区别与使用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#process-nextTick"><span class="nav-text">process.nextTick()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#setTimeout-%E5%92%8CsetImmediate"><span class="nav-text">setTimeout()和setImmediate()</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#16-Promise-%E5%8E%9F%E7%90%86"><span class="nav-text">16.Promise 原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8"><span class="nav-text">链式调用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#reject"><span class="nav-text">reject</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86"><span class="nav-text">异常处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Finally%E6%96%B9%E6%B3%95"><span class="nav-text">Finally方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#resolve-%E6%96%B9%E6%B3%95%E5%92%8C-reject-%E6%96%B9%E6%B3%95"><span class="nav-text">resolve 方法和 reject 方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Promise-all"><span class="nav-text">Promise.all</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Promise-race"><span class="nav-text">Promise.race</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-text">总结</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A1%A5%E5%85%85%E8%AF%B4%E6%98%8E"><span class="nav-text">补充说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="nav-text">参考资料</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%8C%E6%95%B4-Promise-%E6%A8%A1%E5%9E%8B"><span class="nav-text">完整 Promise 模型</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#17-Generators%E5%8E%9F%E7%90%86"><span class="nav-text">17.Generators原理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-Generators-%E7%AE%80%E5%8D%95%E4%BB%8B%E7%BB%8D"><span class="nav-text">1.Generators 简单介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-Generators-in-C"><span class="nav-text">2.Generators in C#</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hxy"
      src="/images/Robben.gif">
  <p class="site-author-name" itemprop="name">hxy</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">80</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">120</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/huxingyi1997" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;huxingyi1997" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huxingyi1997@zju.edu.cn" title="E-Mail → mailto:huxingyi1997@zju.edu.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-frog"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hxy</span>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共1039.2k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'pQsO3ySbU4VtWN2j1FLA74Ha-gzGzoHsz',
      appKey     : 'QYacMDY2VY7Wazprg1X6FiUv',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

  
  <!-- 动态背景特效 -->
  <!-- 樱花特效 -->
    <script async src="/js/src/sakura.js"></script>
    <script async src="/js/src/fairyDustCursor.js"></script>
</body>
</html>
